开发者

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:

  1. Make 2 hibernate.cfg.xml
  2. In HibernateUtil class where you build your sessionFactory object. Build 2 SessionFactory object. Make getter methods of both sessionFactory object.
  3. 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:

  1. Use 2 SessionFactories, but you can then hardly define it as "at a time"
  2. Use Hibernate interceptor that will do changes to the other database when some entity is changed
  3. 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")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜