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

soc picture soc · Aug 31, 2011 · Viewed 24.9k times · Source

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

@Entity(name="Foo")
@Table (name="Bar")
class Baz

What should I use, which ones are optional?

In my specific case I have a class User and a class Group, which have additional requirements (as far as I understand) because they are reserved words in SQL.

How would a working solution look like and with which name would I refer to the entity when writing queries?

Update: I added name="GROUPS" to both annotations in Group and did the same for User, but now I get this error:

Exception Description: The table [USERS] is not present in this descriptor.
Descriptor: RelationalDescriptor(example.Group --> [DatabaseTable(GROUPS)])

and this error

Internal Exception: java.sql.SQLException: Table not found in statement [SELECT ID, MAXIMUMROLE, MEMBERSHIPS_ID FROM USERS]

Answer

Dhanush Gopinath picture Dhanush Gopinath · Aug 31, 2011

@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