Sample Code
You can check out sample code from the MyBatis repository on Github.
Any of the samples can be run with JUnit 4.
The sample code shows a typical design where a transactional service gets domain objects from a data access layer.
The service is composed by an interface FooService.java
and an implementation FooServiceImpl.java
.
This service is transactional so a transaction is started when its method
is called and commited when the method ends without throwing a unchecked exception.
public class FooServiceMapperImpl implements FooService {
@Inject
private UserMapper userMapper;
@Transactional
public User doSomeBusinessStuff(String userId) {
return this.userMapper.getUser(userId);
}
}
Notice that transactional behaviour is configured with the
@Transactional
annotation.
This service calls a data access layer built with MyBatis. This layer
is composed by a MyBatis mapper interface UserMapper.java
and a DAO composed by its interface UserDao.java
and its implementation UserDaoImpl.java
The database access layer has been implemented using a mapper and a Dao that
internally uses a SqlSession
.
Sample test | Description |
---|---|
SampleBasicTest
|
Shows you the recommended and simplest configuration based on a mapper. |
SampleSqlSessionTest
|
Shows how to hand code
a DAO using a managed
SqlSession
|
Please have a look and run the sample code to see MyBatis-Guice in action.