I am learning hibernate and have some questions about the differences between Entity and Table, and how they work together/independently?
Case 1:
@Entity
public class Person{
}
My understanding -
Entity name - Person
Table name in db - person
Case 2:
@Entity(name = "people")
public class Person{
}
My understanding -
Entity name - people
Table name in db - people
Case 3:
@Entity
@Table(name="people")
public class Person{
}
My understanding -
Entity name - Person
Table name in db - people
Case 4:
@Entity(name = "person")
@Table(name = "people")
public class Person{
}
My understanding -
Entity name - person
Table name in db - people
Case 5:
@Table(name="people")
public class Person{
}
My understanding -
Entity name - ??
Table name in db - people
Is my understanding of these five cases correct? Is there anything else I should know about the working of Entity and Table?
>Solution :
@Entity is used to declare a class can be managed by Hibernate. It also defines the entity name through its name attribute which is the name that we use to refer to when writing JPQL/HQL queries. If the entity name is not specified , it is default to the unqualified name of that entity class.
For example :
@Entity(name="People")
public class Person{
}
Then I need to use People to refer to this entity when writing a JPQL query :
select p from People p;
@Table defines the actual DB table name that an @Entity is mapped to through its name attribute. If it is not specified , its default value will be equal to the entity name (i.e @Entity ‘s name attribute)
Also @Table only make senses if @Entity is defined . Otherwise , just defining @Table without @Entity (i.e case 5) does not have any effect.
So to to summaries:
Case 1:
@Entity
public class Person {
}
Entity name = Person
DB Table name = Person
Case 2:
@Entity(name = "people")
public class Person {
}
Entity name = people
DB Table name = people
Case 3:
@Entity
@Table(name="people")
public class Person{
}
Entity name = Person
DB Table name = people
Case 4:
@Entity(name = "person")
@Table(name = "people")
public class Person{
}
Entity name = person
DB Table name = people
Case 5: Invalid