Search code examples
javahibernatesessionsessionfactory

Is it possible to save object in two different schemas using single hibernate session?


I am trying to persist person object into two different schemas using single hibernate session as follows

I have Person Class having certain fields in it

@Entity
public class Person {
    @Id
    @GeneratedValue
    private Integer id;
    @Column(name="firstname")
    private String firstName;
    @Column(name="lastname")
    private String lastName;
    @Column(name="age")
    private int age;

//getters and setters methods

Now I need to save the object into two different schemas using single hibernate session. Can this happens, can anybody have any idea please help me.


Solution

  • I have answered my question

    Its not possible using same session for persist objects into two different schemas.

    I have done like below:

    I have create two hibernate configuration files for the two different schemas you need to persist the object.

    Here is the code snippet:

    Configuration config1 = new Configuration().configure(configfile1);
    Configuration config2 = new Configuration().configure(configfile2);
    

    I have opened the sessionfactory's by using both configuration instances

    SessionFactory sessionFactory1 = config1.buildSessionFactory(); 
    SessionFactory sessionFactory2 = config2.buildSessionFactory();
    

    I have opened two new sessions from sessionFactory instances

    Session session1 = sessionFactory1.openSession();
    Session session2 = sessionFactory2.openSession();
    

    Now I have persisted the objects to two different schemas.

    But Not sure whether this is correct way to handle.

    Thanks