Getting Started

This chapter will show you in a few steps how to install and setup MyBatis-CDI.


To use the MyBatis-CDI module, you just need to include the mybatis-cdi-2.0.2-SNAPSHOT.jar file and its dependencies in the classpath.

If you are using Maven just add the following dependency to your pom.xml:


Quick Setup

First, switch CDI on by adding a beans.xml file to your META-INF directory.

Next, to use MyBatis with CDI you need to provide at least two things: an SqlSessionFactory and a CDI bean that requires a MyBatis mapper injection.

Create a producer method that returns an application scoped SqlSessionFactory annotated with @SessionFactoryProvider:

import jakarta.enterprise.inject.Produces;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.cdi.SessionFactoryProvider;
public class SqlSessionFactoryProvider {

  public SqlSessionFactory produceFactory() {
    SqlSessionFactory factory = create the factory instance ....
    return factory;


Assume you have a mapper interface defined like the following (Note that the mapper must be annotated with @Mapper):

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

You can inject it into a CDI bean just as any other dependency using @Inject :

import jakarta.inject.Inject;
public class FooServiceImpl implements FooService {

@Inject UserMapper userMapper;

public User doSomeStuff(String userId) {
  return this.userMapper.getUser(userId);