Creating Entities¶
What is an Entity?¶
An entity in JPA is a lightweight persistence domain object. Each entity represents a table in a relational database, and each instance of an entity represents a row in that table.
Creating a Basic Entity¶
Here’s an example of a simple entity:
import javax.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String email;
// Getters and setters
}
Key Annotations¶
@Entity
: Specifies that the class is an entity.@Table
: Specifies the table in the database with which this entity is mapped.@Id
: Specifies the primary key of the entity.@GeneratedValue
: Specifies how the primary key should be generated.@Column
: Specifies the details of the column to which a field or property will be mapped.
Relationships Between Entities¶
JPA provides annotations to define relationships between entities:
1. One-to-Many Relationship¶
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
private List<Comment> comments;
}
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
}
2. Many-to-Many Relationship¶
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> courses;
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy = "courses")
private Set<Student> students;
}
Best Practices¶
Use meaningful names for entities and fields.
Implement equals() and hashCode() methods for entities.
Consider using a base class for common fields like id, createdAt, updatedAt.
Use appropriate fetch types for relationships to optimize performance.
Be cautious with bidirectional relationships to avoid infinite loops in JSON serialization.
In the next section, we’ll look at how to create repositories to interact with these entities.