Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get annotated hibernate tablename from POJO

I have an entity which is declared roughly like:

@Entity
@Table(name = "myUserTable")
public class User implements Serializable { ... }

I'm making a generic DAO class, and in doing so I'd like to retrieve the "myUserTable" name. Is there any way I can reach this name?

like image 907
niklassaers Avatar asked Aug 24 '09 07:08

niklassaers


People also ask

What is @table annotation in spring boot?

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 catalog, and its schema, and enforce unique constraints on columns in the table.

What is the difference between entity name and table name in hibernate?

Entity means the class which you will use in your program and Table means the actual Database table that you will access through your program. Hibernate being an ORM requires you to declare the relationship between the tables and the classes mapping to them.

What is @ID annotation in hibernate?

The @Id annotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of the current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation.

Is @column annotation necessary?

Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.


2 Answers

Easy enough using general reflection:

import javax.persistence.Table;

.....

Class<?> c = User.class;
Table table = c.getAnnotation(Table.class);
String tableName = table.name();
like image 105
skaffman Avatar answered Sep 22 '22 20:09

skaffman


Similar to Get the table name from the model in Hibernate

Table table = Entity.class.getAnnotation(Table.class);
String tableName = table.name();
like image 37
n002213f Avatar answered Sep 23 '22 20:09

n002213f