What's the difference between the name argument in @Entity and @Table when using JPA?

后端 未结 3 1712
Happy的楠姐
Happy的楠姐 2020-12-24 01:55

I\'m using JPA2 and both @Entity and @Table have a name attribute, e. g.:

@Entity(name=\"Foo\")
@Table (name=\"Bar\")
         


        
相关标签:
3条回答
  • 2020-12-24 02:16

    @Table is optional. @Entity is needed for annotating a POJO class as an entity, but the name attribute is not mandatory.

    If you have a class

     @Entity
     class MyEntity {}
    

    A table with name "MyEntity" will be created and the Entity name will be MyEntity. Your JPQL query would be:

     select * from MyEntity
    

    In JPQL you always use the Entity name and by default it is the class name.

    if you have a class

     @Entity(name="MyEntityName")
     @Table(name="MyEntityTableName")
     class MyEntity {}
    

    then a table with name MyEntityTableName is created and the entity name is MyEntityName.

    Your JPQL query would be :

     select * from MyEntityName
    
    0 讨论(0)
  • 2020-12-24 02:35

    The name in @Entity is for JPA-QL queries, it defaults to the class name without package (or unqualified class name, in Java lingo), if you change it you have to make sure you use this name when building queries.

    The name in @Table is the table name where this entity is saved.

    0 讨论(0)
  • 2020-12-24 02:41

    @Entity is useful with model classes to denote that this is the entity or table

    @Table is used to provide any specific name to your table if you want to provide any different name

    Note: if you don't use @Table then hibernate consider that @Entity is your table name by default

    @Entity    
    @Table(name = "emp")     
    public class Employee implements java.io.Serializable { }
    
    0 讨论(0)
提交回复
热议问题