In this blog post, we will explore the purpose and usage of JPA @Entity and @Table annotations, understanding how they facilitate the persistence of Java entities.
Jakarta Persistence API (JPA) is a powerful technology that simplifies the interaction between Java applications and relational databases. At the heart of JPA lies the @Entity and @Table annotations, which enable developers to seamlessly map Java objects to database tables.
@Entity Annotation: Defining Persistent Entities
The @Entity annotation is a fundamental building block of JPA, indicating that a Java class is a persistent entity, representing a database table. Each instance of an @Entity class corresponds to a row in the associated database table, and the class's fields are mapped to the table columns.
The below diagram shows the mapping between the Student persistent class and the student database table:Here's an example:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// getters and setters
}
In this example, the Product class is marked as an @Entity, representing the product table in the database. If we don't use @Table annotation to customize the table mapping then JPA gives a name to the table as a class.
@Table Annotation: Customizing Table Mapping
The @Table annotation provides options to customize the mapping of an entity to a database table. It allows you to specify the name of the table, the schema, and other attributes related to the database table.
For instance: In the below code snippet, we are specifying the students table name in the database.@Entity @Table(name = "student") public class Student { }
@Entity
@Table(name="student", schema="college")
public class Student {
// fields, getters and setters
}
We can also define the unique constraints using uniqueConstraints attribute of @Table annotation:
import jakarta.persistence.*;
@Entity
@Table(
name = "posts",
uniqueConstraints = {@UniqueConstraint(columnNames = {"title"})}
)
public class Post {
@Id
@GeneratedValue(
strategy = GenerationType.IDENTITY
)
private Long id;
private String title;
private String description;
private String content;
}
Conclusion
The @Entity and @Table annotations are fundamental to JPA, enabling Java developers to seamlessly map Java objects to database tables and establish relationships between entities. By mastering these annotations and understanding their various attributes, developers can create sophisticated and efficient database-driven applications using JPA.
Leveraging the power of JPA simplifies the data access layer and ensures smooth interaction between the Java application and the underlying database.
Comments
Post a Comment
Leave Comment