Implementing a service class

As mentioned before, we need to add some transaction and session handling code in order to use mapper classes. This can be done in service classes. A service class is simply a class that performs some kind of business logic (in contrast, a mapper class performs persistence-only logic). The following is an example of a class that encapsulates session handling in order to avoid coupling the UI with MyBatis-related logic:

public class MessageService {

public static List<Message> findAll() {
try (SqlSession session =
MyBatisService.getSqlSessionFactory().openSession()
) {
MessageMapper mapper =
session.getMapper(MessageMapper.class)
;
return mapper.findAll();
}
}

public static void save(Message message) {
try (SqlSession session = MyBatisService.getSqlSessionFactory().openSession()) {
MessageMapper mapper = session.getMapper(MessageMapper.class);
mapper.save(message);
session.commit();
}
}
}

Each persistence unit of work should be enclosed by an active session. Additionally, for insert or updates, we need to commit the transaction to the database.

MyBatis is a powerful and mature framework you should keep in mind when deciding on technologies. There are many other features, such as the possibility to map methods to SQL stored procedures or using XML files (or even the Apache Velocity scripting language) to define the SQL queries, which is useful when the queries require multiple lines or need to be formed dynamically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset