SpringMVC 集成 MyBatis

吐嘈一下 Mapper 在 IDEA 里注入识别不了就加 @Repository 的人,咋不去加个 @Controller 呢?自己做啥都不知道能跑就行的人,活该做一辈子码农。

前言

因为 MyBatis 基本只有国人在用,IDEA 对于 MyBatis 的支持并不好,需要安装 MyBatis 相关插件才能正确识别 Mapper 注入,我就自己写了一个 MyBatis4II,可以在插件市场搜到。

集成

  • 依赖
    org.mybatis:mybatis 与 org.mybatis:mybatis-spring 以及 spring-jdbc,前两者提供 MyBatis 核心功能以及 Spring 集成相关功能,后面支持事务操作。

  • 根应用上下文

...
@EnableTransactionManagement(
        mode = AdviceMode.PROXY,
        proxyTargetClass = true
)
@MapperScan({"com.seliote.mt.mapper"})
...
    @Bean
    public TransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        // 扫描的 XML Mapper 路径
        final String xmlMapperLocation = "classpath:mapper/*.xml";
        // 优先使用 SqlSessionFactoryBean 而非 SqlSessionFactoryBuilder
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 相关配置对象
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // 将数据库中的下划线命名自动转为驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(xmlMapperLocation));
        LOGGER.debug("Create bean SqlSessionFactory, xml mapper location: {}", xmlMapperLocation);
        return sqlSessionFactoryBean.getObject();
    }
...
  • 实体类就 POJO 即可
...
@Data
public class SysIndexEntity {

    private String id;
    private Integer type;
    private Integer status;
    private String msg;
    private LocalDateTime createDate;
    private LocalDateTime lastModifiedDate;
    ....
}
  • 定义 Mapper 与 xml,文件名随意
public interface SysIndexMapper {

    SysIndexEntity findOne();

    Integer insert();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.seliote.mt.mapper.SysIndexMapper">

    <select id="findOne" resultType="com.seliote.mt.entity.SysIndexEntity">
        SELECT *
        FROM sys_index
        LIMIT 0, 1
    </select>

    <insert id="insert">
        INSERT INTO sys_index
        VALUES (UUID(), "33", "23", "TEST3", "2020-05-03 23:58:53", "2020-05-03 23:58:53")
    </insert>

</mapper>
原文地址:https://www.cnblogs.com/seliote/p/12833346.html