JPA

Understanding @Entity and @Table Annotations in JPA

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.

Avatar

Neelabh

About Author

As Neelabh Singh, I am a Senior Software Engineer with 6.6 years of experience, specializing in Java technologies, Microservices, AWS, Algorithms, and Data Structures. I am also a technology blogger and an active participant in several online coding communities.

You may also like

Blog JPA

Transitioning from Java Persistence API (JPA) to Jakarta Persistence: A Comprehensive Guide

What is Jakarta Persistence? This is because the Java Persistence API (JPA) was renamed to Jakarta Persistence in 2019¹. The
Blog JPA

Understanding JPA and Hibernate in Spring Boot Applications

Introduction In this blog post, we will explore two key technologies used in Java applications for interacting with databases: the