Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of @Table annotation in JPA?

Tags:

hibernate

jpa

The whole point of using these annotations is to be independent of the database provider, and not to regenerate the JAR archive.

If I hardcore the @Table (name = myDatabase.myTableName) I don't see the point of using hibernate in the first place. If I do decide to switch to a different database provider, then I will have to modify the @Table (name = myDatabase.myTableName) annotation in my class , and recompile the application .

like image 870
Emily Avatar asked Jun 09 '16 15:06

Emily


People also ask

Is @table annotation mandatory?

When you create a new entity you have to do at least two things annotated it with @Entity create an id field and annotate it with @Id Anything else is optional, for example, the table name is derived from entity class name (and therefore @Table annotation can be optional), table's columns are derived from entities ...

Is @column annotation necessary?

Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.

What is the use of @ID annotation?

The @Id annotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of the current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation.

What will happen if @table is not specified while defining pojo?

If no @Table is defined the default values are used: the unqualified class name of the entity. For example if you have: @Entity public class MyTest{ ... Your table will have the name my_test in your database.


1 Answers

@Table Annotation: The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.

The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table. For now we are using just table name which is EMPLOYEE.

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
   @Id @GeneratedValue
   @Column(name = "id")
   private int id;
}

Just add the table name here and database name is not required to give in java code. http://docs.oracle.com/javaee/5/api/javax/persistence/Table.html

like image 159
Sudhakar Avatar answered Sep 22 '22 09:09

Sudhakar