Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate switch schema programmatically

I'm working at the moment on a new project which has following requirement:

Several database schemas are holding the same tables with identical structure (in short: one entity for multiple schemas).

Is it possible to switch between those schemas by code? Want I want to achieve is:

User selects schema B and updates some entities in this. After this he does a insert in schema A and so on. I know that I could do this by basic JDBC by providing the schema to the statements but if I can avoid that I would do so.

Maybe some other java ORM can do this? I'm only familiar with JPA / Hibernate.

Regards

like image 496
onigunn Avatar asked Jul 14 '11 19:07

onigunn


1 Answers

You can use separate SessionFactorys or EntityManagerFactorys, one for each schema. Since you said that the user selects schema A or B, you can use something like this:

public enum Schema {
    A, B
}

public EntityDaoImpl {

    // Create and populate the map at DAO creation time (Spring etc.).
    private Map<Schema, SessionFactory> sessionFactoryBySchema = ...; 

    private Session getSession(Schema schema) {
        SessionFactory sessionFactory = sessionFactoryBySchema.get(schema);
        return sessionFactory.getCurrentSession(); // ... or whatever
    }

    public void saveEntity(Schema schema, Entity entity) {
        getSession(schema).save(entity);
    }
}
like image 194
Nicolae Albu Avatar answered Oct 23 '22 07:10

Nicolae Albu