Name attribute in @Entity and @Table
Here is a real-life example with some good practice tips, as I just spent 2 hours trying to figure out why my HQL query was throwing the
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: MyEntity is not mapped [SELECT e FROM MyEntity e ...
exception when I used the my_entity
in the @Entity annotation.
@Entity name is used to refer your entity throughout the application, notably in HQL queries, and @Table is the actual DB table name, for example:
@Entity(name = "SomeThing")
@Table(name = "some_thing")
public class SomeThing {
@Id
private Long id;
}
, then your JPA repository might be something like:
@Repository
public interface BikeOfferRepository extends JpaRepository<SomeThing, Long> {
/** A contrived example as in reality you'd use built-in
query for this type of select */
@Query("SELECT o FROM SomeThing WHERE o.id =:id") // <-- Here you use "SomeThing", the entity name in HQL
SomeThing findAllByBikeOwner(@Param("id") Long id);
}
BTW, it's a good pracitce to use class name or camel-case name for the entity name and lowercase spaced with underscores for a table and column names (as in my example above). See here more on DB naming conventions: https://www.sqlshack.com/learn-sql-naming-conventions/.
And in the actual database (or if you use old-style JDBC queries) you'd use:
select * from some_thing where id=xxx;
@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 and @Entity
must
@Entity
@Table(name = "emp")
public class Employee implements java.io.Serializable
{
}
@Entity(name = "someThing") => this name will be used to name the Entity @Table(name = "someThing") => this name will be used to name a table in DB
So, in the first case your table and entity will have the same name, that will allow you to access your table with the same name as the entity while writing HQL or JPQL.
And in second case while writing queries you have to use the name given in @Entity and the name given in @Table will be used to name the table in the DB.
So in HQL your someThing will refer to otherThing in the DB.
@Entity(name = "someThing")
=> this name will be used to identify the domain ..this name will only be identified by hql
queries ..ie ..name of the domain object
@Table(name = "someThing")
=> this name will be used to which table referred by domain object..ie ..name of the table