Learn about @Entity and @Table annotation in JPA

In tutorial basic about Hibernate and basic about JPA, I’ve called classes that map the clazz tables and students in the database as Java objects. But in essence, I have to call them are the entities because they represent tables in the database and each of them is a row in those tables.

These classes use the @Entity and @Table annotations. For more information, I would like to clarify the two annotations in this tutorial.

@Entity annotation

To talk about @Entity annotation, first of all, you should know about POJO (Plain Old Java Object) and JavaBean.

POJOs are Java objects that are not constrained by anything else. They are not implemented or extended from any other class and they do not contain any annotations in themselves. They contain only the attributes, Setter, Getter methods, and may include both override toString() and equals() methods.

For example:

As for JavaBean, they are actually POJOs with at least one constructor without parameters and they can only implement the Serializable interface.

OK, what I just mentioned is enough to talk about @Entity annotation.

In fact, the main use of @Entity annotation is to make a JavaBean become an entity so that we can manipulate the database using this entity. That’s all, if you do not use @Entity annotation then when you run the program, you will get the error right away.

If you do not use @Table annotation in your entity, the default table name in the database will be the class name of the entity.

In this case, the table name in the corresponding database would be clazz.

We can also rename the table by declaring the name attribute in @Entity annotation. In this case, the name of the entity will also change.

Here, the table name will be the class and the name of the entity will also change to Class.

@Table annotation

In case, you just want to change the name of the database table to use in your application without changing the name of the entity, using @Table annotation will meet your needs.

Here, the name of the table that we will use is the class and the entity name is still Clazz.

Add Comment