What is the use of @Table annotation in JPA?

42,222

@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

Share:
42,222

Related videos on Youtube

Emily
Author by

Emily

Updated on July 09, 2022

Comments

  • Emily
    Emily over 1 year

    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 .

    • Neil Stockton
      Neil Stockton over 7 years
      What you say simply reflects why many people (including myself) don't recommend putting database-specific info into Java code, and instead keep it in XML, so everything is much more portable. There are some people out there who prefer to have everything in their Java file and make the code look harder to read :-S i.e personal preference, so use it if you want otherwise use XML, or rely on the default that JPA defines
    • JB Nizet
      JB Nizet over 7 years
      Why would you put "myDatabase" in the name in the first place, instead of just the table name? And what would prevent you from using the same table name in Oracle, PostgreSQL and MySQL? Assuming you'll ever switch, which won't happen.
  • Emily
    Emily over 7 years
    Thank You. But where do I specify the database name (schema) ? In the link you provided it should still go in annotation @Table(name="CUST", schema="RECORDS")
  • JB Nizet
    JB Nizet over 7 years
    The schema is typically specified in the JDBC connection URL, or implied by the name you use to connect to the database.

Related