Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect two or more applications to the same database using Hibernate

I am planning to build a desktop application that will use Hibernate and MySQL as its datasource. I would like to execute the desktop application on multiple machines but I want them all to read/write to the same MySQL database. Is this even possible? My concern is about concurrency issue when two applications is trying to access/modify the same information. Is there an alternative solution for multiple ORM applications to have real-time database syncronisation (if a single database is not allowed)?

There were a few similar question to mine on stackoverflow but their answers do not satisfy me.

like image 639
gigadot Avatar asked Aug 30 '13 16:08

gigadot


People also ask

How does Hibernate connect to database?

It represents the classname of a custom ConnectionProvider which provides JDBC connections to Hibernate. It is used to set the JDBC transaction isolation level. It enables auto-commit for JDBC pooled connections.

Is Hibernate better than JDBC?

Both Hibernate & JDBC facilitate accessing relational tables with Java code. Hibernate is a more efficient & object-oriented approach for accessing a database. However, it is a bit slower performance-wise in comparison to JDBC.

Why use Hibernate instead of JDBC?

The short answer on the fundamental difference between JDBC and Hibernate is that Hibernate performs an object-relational mapping framework, while JDBC is simply a database connectivity API. The long answer requires a history lesson on database access with Java.

Is JDBC and Hibernate same?

JDBC is database dependent i.e. one needs to write different codes for different database. Whereas Hibernate is database independent and same code can work for many databases with minor changes.


1 Answers

You can have multiple hibernate-based apps talking to the same database. For the most part, this is pretty much the same as running multiple threads talking to the same database.

The most common problem you are likely to see will occur if your hibernate configuration is using a second-level cache. When hibernate is configured with a second-level cache, it assumes that the cache is consistent with the underlying database. When you have a single application attaching to the database, the second-level cache can exist in the local RAM of the app server and everything is good.

If you have multiple servers (whether they are running the same application or different ones), you need to have a single second-level cache that is shared by all of the servers. Or you need to not use a second-level cache.

Several distributed cache solutions for hibernate's second-level cache are available - google will help you research your various options if you decide to go this route.

Same argument applies to query cache as well.

like image 187
Rob Avatar answered Oct 21 '22 21:10

Rob