如何与“ Micronaut”一起使用“ MyBatis-CDI”

时间:2019-05-06 17:09:08

标签: cdi mybatis micronaut

我尝试将“ MyBatis-CDI”与“ Micronaut”一起使用,但无法注入Mapper。

io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [docloud.mappers.UserMapper] exists.

我认为问题出在SqlSessionFactory中,因为我不能使用@ApplicationScoped

public class MyBatisFactory {

    @Context
    @Produces
    @SessionFactoryProvider
    SqlSessionFactory sqlSessionFactory() throws IOException {
        String resources = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resources);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

}

映射器界面

import org.mybatis.cdi.Mapper;

@Mapper
public interface DocumentMapper {
...
}

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="org.postgresql.Driver" />
                <property name="url" value="------------"/>
                <property name="username" value="-------"/>
                <property name="password" value="-------"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/UserMapper.xml" />
        <mapper resource="mappers/DocumentMapper.xml" />
        <mapper resource="mappers/PermissionMapper.xml" />
    </mappers>
</configuration>

您有什么想法,如何解决?仅当要使用 MyBatis-CDI

时才存在该问题。

1 个答案:

答案 0 :(得分:0)

尝试在给定的代码下使用mybatis。

import io.micronaut.context.annotation.Context;
import io.micronaut.context.annotation.Factory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;

@Factory
public class MybatisFactory {

    final DataSource dataSource;

    public MybatisFactory(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Context
    SqlSessionFactory sessionFactory() {

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment  = new Environment("developpment", transactionFactory, dataSource);

        Configuration configuration = new Configuration(environment);
        configuration.addMappers("issue.service");

        return new SqlSessionFactoryBuilder().build(configuration);
    }
}

application.yml

datasources:
    default:
        url: jdbc:mysql://localhost:3306/test
        username: root
        password: secret
        driverClassName: com.mysql.jdbc.Driver