Introduction
In this blog post, we will explore two key annotations used in Java Persistence API (JPA): @Entity
and @Table
. We will discuss what they are, how they work, and when to use each one.
What is the @Entity Annotation?
The @Entity
annotation is used to mark a Java class as an entity, meaning that it is a lightweight persistence domain object. Basically, it’s a way to declare a Java class as a representation of a table in your database. Once a class is annotated with @Entity
, JPA recognizes it as an entity and manages it as such.
What is the @Table Annotation?
The @Table
annotation is used to provide additional information about the table in the database that the entity is mapped to. For example, you can use it to specify the name of the table, the catalog, and the schema. If @Table
is not specified for an entity class, the default values are used: the unqualified name of the entity class is used as the table name, and the default catalog and schema for the user are used.
Code Examples
Here’s an example of how you might use these annotations:
@Entity
@Table(name = "employees", catalog = "myDatabase", schema = "public")
public class Employee {
// fields, getters, setters...
}
In this example, the Employee
class is marked as an entity with @Entity
, and it’s mapped to the “employees” table in the “myDatabase” catalog and “public” schema with @Table
.
Conclusion
In conclusion, the @Entity
and @Table
annotations in JPA provide a powerful way to map your Java classes to your database tables. Understanding when and how to use these annotations can help you create more flexible and efficient JPA entities.