O'Reilly logo

Java Persistence with MyBatis 3 by K. Siva Prasad Reddy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transaction management using Spring

Using plain MyBatis, you need to write the code for transaction handling, such as committing or rolling back the database operations.

public Student createStudent(Student student) 
{
  SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
  try {
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    mapper.insertAddress(student.getAddress());
    mapper.insertStudent(student);
    sqlSession.commit();
    return student;
  }
  catch (Exception e) {
    sqlSession.rollback();
    throw new RuntimeException(e);
  }
  finally {
    sqlSession.close();
  }
}

Instead of writing this boiler plate for each method, we can use the Spring's annotation-based transaction-handling mechanism.

To be able to utilize the Spring's transaction ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required