Let's define a couple of entities to use in our example. We will create an entity Todo to manage todos. A simple example is shown as follows:
@Entity
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userid")
private User user;
private String title;
private String description;
private Date targetDate;
private boolean isDone;
public Todo() {// Make JPA Happy
}
}
Important things to note are as follows:
- Todo has a title, a description, a target date, and a completion indicator (isDone). JPA needs a constructor.
- @Entity: The annotation specifies that the class is an entity.
- @Id: Specifies that ID is the primary key of the entity.
- @GeneratedValue(strategy = GenerationType.AUTO): The GeneratedValue annotation is used to specify how the primary key is generated. In this example, we are using a strategy of GenerationType.AUTO. This indicates that we would want the persistence provider to choose the right strategy.
- @ManyToOne(fetch = FetchType.LAZY): Indicates a many-to-one relationship between User and Todo. A @ManyToOne relationship is used on one side of the relationship. FetchType.Lazy indicates that the data can be lazily fetched.
- @JoinColumn(name = "userid"): The JoinColumn annotation specifies the name of the foreign key column.
The following snippet shows the User entity:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userid;
private String name;
@OneToMany(mappedBy = "user")
private List<Todo> todos;
public User() {// Make JPA Happy
}
}
Important things to note are as follows:
- The user is defined as an entity with the userid and name attributes. The ID is the primary key, which is autogenerated.
- The @OneToMany(mappedBy = "user"): OneToMany annotation is used on the many side of a many-to-one relationship. The mappedBy attribute indicates the property of the owner entity of the relationship.