Henry Jones
Henry Jones

Reputation: 53

Hibernate: dynamically set table name

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.

Upvotes: 3

Views: 6282

Answers (3)

helloworld1970
helloworld1970

Reputation: 69

I tried a lot of ways, only it was the simplest:

Session session = super.getSession();
    SQLQuery query = session.createSQLQuery("raw sql");
    query.setParameter(":abc", "value");
    query.addEntity(Some.class);
    return query.list();

Upvotes: 0

Shawn
Shawn

Reputation: 1

This more like an schema design issue, those tables with similar definition and only name is different due to some attribute, why not add this attribute into the table schema and combine all those tables into one? Then you just need add this field into a where clause.

Upvotes: 0

ssedano
ssedano

Reputation: 8432

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.

Upvotes: 1

Related Questions