Search code examples
cdimybatis

How to use MyBatis with CDI


I am writing a web application and I am using MyBatis framework for persistence. I want to use CDI to inject the mappers easily and to manage the transaction declaratively.


Solution

  • MyBatis has official CDI support:

    Mapper declaration:

    @Mapper
    public interface UserMapper {
      @Select("SELECT * FROM users WHERE id = #{userId}")
      User getUser(@Param("userId") String userId);
    } 
    

    Mapper Usage:

    public class MyService {
    
        @Inject UserMapper userMapper;
    
        public User doSomeStuff(String userId) {
           return this.userMapper.getUser(userId);
        }
    }
    

    More information in docs: http://mybatis.org/cdi/