Spring – How to configure multiple schemas with Hibernate

hibernatehibernate-criteriahibernate-mappingormspring

We have got a requirement for multiple schemas in Hibernate.

In our project, we need to connect to multiple schemas based on the username and password. But how to configure multiple schemas in Hibernate?

Please let me know if there's a way.

Best Answer

You can specify it by schema element while defining table for your entity.

@Table(name="TABLE_NAME", schema="SCHEMA_NAME")

Else, you can use separate EntityManager pointing to respective schema & then use the same entity, as their structure is similar.


Edit : You can have separate configuration files for each schema & then build SessionFactory from it, below is some pseudo-code for it.

SessionFactory sf_1 = new  Configuration().configure("schema1config.cfg.xml").buildSessionFactory();
SessionFactory sf_2 = new Configuration().configure("schema2config.cfg.xml").buildSessionFactory();

session_1 = sf_1.openSession();  //-- Similarly for other

You can refer this link for further details to map multiple schema, but it isn't hibernate specific.