Delaram Mahmoudi Sari
Delaram Mahmoudi Sari

Reputation: 13

Difference between classToTableName & tableName & collectionTableName in Hibernate NamingStrategy?

I am using hibernate annotations and I want to change class(table) names to "t_xx". but I do not know to use which of them(classToTableName & tableName & collectionTableName).

Upvotes: 1

Views: 300

Answers (1)

Learner
Learner

Reputation: 21425

You have to create a custom Naming Strategy by extending DefaultNamingStrategy class.

Here is the explanation on these methods:

  • classToTableName(java.lang.String) : When you have declared a class using @Entity and without any `@Table(name="...") then this method will be called to get the name of the DB table from your class name.

  • collectionTableName(...) : When a join table is needed then this method will be called by hibernate.

  • tableName(java.lang.String) : When you have declared an entity along with `@Table(name="table_name"), then hibernate calls this method by passing the value of name attribute to this method.

If you have not declared any naming strategy then hibernate uses DefaultNamingStrategy

So extend this class and override the method like this:

public String  classToTableName(String className) {
   return "t_"+super.classToTableName(className);
}


public String collectionTableName(String ownerEntity, String ownerEntityTable, String associatedEntity, String associatedEntityTable,String propertyName) {
   return "t_"+super.collectionTableName(ownerEntity,ownerEntityTable,associatedEntity,associatedEntityTable,propertyName);
}

If needed you can override the tableName(String) if you want to change the value of the attribute for name in @Table annotation.

Upvotes: 1

Related Questions