开发者

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 开发者_如何学CI can avoid that I would do so.

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

Regards


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜