入门

这一章节将向你展示 MyBatis-CDI 的安装步骤。

安装

要使用 MyBatis-CDI 模块,你只需要将 mybatis-cdi-2.0.2.jar 文件和它的依赖置于类路径中。

如果你使用 Maven, 只需要将以下依赖添加到你的 pom.xml 中:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-cdi</artifactId>
  <version>2.0.2</version>
</dependency>

快速搭建环境

首先,开启 MyBatis-CDI 需要向你的 META-INF 文件夹中添加 beans.xml 文件。

接下来,使用 MyBatis-CDI 至少需要两样东西: SqlSessionFactory 和用于注入 Mybatis mapper 的 CDI 组件(bean).

创建一个生成器(producer)方法,返回一个应用域(application scoped)的 SqlSessionFactory 并带有 @SessionFactoryProvider 注解:

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

  @Produces
  @ApplicationScoped
  @SessionFactoryProvider
  public SqlSessionFactory produceFactory() {
    SqlSessionFactory factory = create the factory instance ....
    return factory;
  }

}

假定你有一个像下面这样的 mapper 接口(注意:必须在 mapper 上添加 @Mapper 注解):

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

你可以使用 @Inject 将任意的依赖注入到 CDI 组件中去:

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

@Inject UserMapper userMapper;

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