Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: dynamically set table name

Tags:

hibernate

I have an entity which should be dynamically persisted to different tables according to some string property representing the table name. Hibernate's Dynamic Models looks like exactly what I want, but I cannot find how to set table name :) Can anybody tell me what I'm missing? Thank's in advance.

P.S.Another found solution is http://java.dzone.com/articles/hibernate-dynamic-table-routin . But I dislike it cause it looks like dirty hack. What if I'll have multiple query parts named as the substring I want to replace.

like image 551
Henry Jones Avatar asked May 23 '26 04:05

Henry Jones


1 Answers

If you are using JPA then you can @PrePersist.

If working with plain Hibernate then take a look at event.

Don't know if it will work for you.

It looks like a NamingStrategy tutorial is what you need.

@Override
public String classToTableName(String className) {
    // your code super.classToTableName()
}


org.hibernate.cfg.NamingStrategy interface.

Hibernate 3.6 has four implementations of this interface:

org.hibernate.cfg.DefaultComponentSafeNamingStrategy
org.hibernate.cfg.DefaultNamingStrategy
org.hibernate.cfg.EJB3NamingStrategy
org.hibernate.cfg.ImprovedNamingStrategy

Implement your code to return the table name.

like image 66
ssedano Avatar answered May 27 '26 23:05

ssedano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!