Mybatis and Spring data with hibernate together

Viewed 640

We have a project which is using Spring data with hibernate as ORM. Now we are introducing new feature for which we want to use Mybatis and eventually replace hibernate with Mybatis in all of the project but in the meanwhile can Mybatis and Hibernate live together for sometime until we make total switch. I am particularly concerned with Mybatis and Hibernate will share connection pool i.e. Hikari CP (default connection pooling that comes with spring boot, yes this project is Spring boot project!). I am not 100% sure that data source will be shared between both of them? So the question is how feasible is to have Mybatis and Hibernate together for some time ?

3 Answers

Honestly I never tested them together - yes both of them on its own plus JDBC, and everything worked properly - but, at first glance, there is no reason why Spring Data JPA with Hibernate and Mybatis cannot share the same connection pool and data source.

First, both frameworks can access and autodetect the same data source and underlying connection pool.

According to your comments, you are probably using Mybatis-Spring-Boot-Starter. This starter will provide you the ability to autodetect the configured data source and register a properly configured SqlSessionFactory with it.

A similar behavior of course is applicable for Spring Data JPA as well.

Moreover neither Mybatis nor Spring Data JPA should impose any restriction - number of connections, etcetera - on the underlying connection pool.

Finally, Spring Data JPA and Mybatis, this last one with the help of the companion library mybatis-spring, both support Spring's annotation-driven transaction management capability, you only need to properly define your @Transactional annotations in your methods.

Despite my recommendation would be, if possible, not to mix in the same service methods your Spring Data repositories and Mybatis mappers, I think there is no reason not to.

Spring Data Hibernate and Mybatis will be able to share the same connection pool, data source, and transaction manager.

However, there are some situations to watch out for, e.g. avoid manipulating the same object loaded by Hibernate with Mybatis.

Account account = AccountRepository.findById( 999 );
account.setAmount(111);
account.setCode(111);
// May use account to read with Mybatis
// But avoid manipulating account with Mybatis
AccountRepository.save( account );

You can get the JDBC connection from a MyBatis session using getConnection() and use it to build an Hibernate session :

  sessionFactory.withOptions().connection(connection).openSession();

You can also get a reference to the underlying connection of an Hibernate Session using the doWork method:

session.doWork(new Work() {    

  @Override
  public void execute(Connection connection) throws SQLException {
Related