How can we store data in two different database at a time using Hibernate?
Interviewer question to me:
How can we store data in two different database at a time开发者_运维技巧 using Hibernate?
I'm not sure but this can be possible:
- Make 2 hibernate.cfg.xml
- In HibernateUtil class where you build your sessionFactory object. Build 2 SessionFactory object. Make getter methods of both sessionFactory object.
- Where you want to insert some data take appropriate sessionFactory object and do the operation.
I don't think there is any built-in feature of Hibernate, but you can either:
- Use 2 SessionFactories, but you can then hardly define it as "at a time"
- Use Hibernate interceptor that will do changes to the other database when some entity is changed
- Use JPA events (which I believe use interceptors under the hood)
In my experience, example for two or more databases from same data source
Main database : hibernate.cfg.xml
<property name="hibernate.connection.url">
jdbc:mysql://ip_adress:3306/main_db
</property>
Alternate database : domain class
@Table(catalog = "alt_db", name = "table_name") // Specify catalog
@Table(catalog = "alt_db2", name = "table_name")
精彩评论