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?
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.
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.
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.
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.
Easy enough using general reflection:
import javax.persistence.Table;
.....
Class<?> c = User.class;
Table table = c.getAnnotation(Table.class);
String tableName = table.name();
Similar to Get the table name from the model in Hibernate
Table table = Entity.class.getAnnotation(Table.class);
String tableName = table.name();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With