美文网首页
在springboot中,mybatis同时使用注解和xml配置

在springboot中,mybatis同时使用注解和xml配置

作者: 宁静的猫 | 来源:发表于2019-05-26 23:14 被阅读0次

    mybatis作为一款优秀的持久层框架,在很多公司的Java项目中,得到了广泛的使用。对于在springboot环境下,mybatis同时支持注解配置和xml配置,下面就通过一个简单的demo介绍一下其配置方法。

    目录结构图如下:


    1558881918648.jpg

    1、首先定义一个Student的实体类:

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    public class Student {
    
        private String name;
    
        private Integer age;
    
    }
    

    2、定义Mapper。其中queryAllByAnnotation()、queryAllByXml()两个方法都实现了查询所有student的功能:

    package com.demo.mybatis_spring.mapper;
    
    //@Repository可以不加,在这里加上是为了消除@Autowire时产生的错误提示
    @Repository
    public interface StudentMapper {
        
        //注解配置
        @Select("select * from student where 1 = 1")
        List<Student> queryAllByAnnotation();
    
        //xml配置
        List<Student> queryAllByXml();
    
    }
    

    3、在Configuration类中配置扫描StudentMapper类,使注解方法queryAllByAnnotation()生效。

    @SpringBootApplication
    @MapperScan("com.demo.mybatis_spring.mapper")
    public class MybatisSpringApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MybatisSpringApplication.class, args);
        }
    
    }
    

    4、在application.properties文件中,配置扫描xml文件StudentMapper.xml。

    mybatis.mapper-locations=classpath*:*Mapper.xml
    

    5、在StudentMapper.xml中,配置queryAllByXml()方法所需要的sql。

    <?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.demo.mybatis_spring.mapper.StudentMapper">
    
        <select id="queryAllByXml" resultType="com.demo.mybatis_spring.model.Student">
            select * from student where 1 = 1
        </select>
    
    </mapper>
    

    6、运行测试类MybatisSpringApplicationTests中的测试方法,两个方法都输出了所有Student的结果,则配置成功。

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MybatisSpringApplicationTests {
    
        @Autowired
        private StudentMapper studentMapper;
    
        @Test
        public void contextLoads() {
            System.out.println(studentMapper.queryAllByAnnotation());
            System.out.println(studentMapper.queryAllByXml());
        }
    }
    

    另外,我在我的项目中也踩过一次很大的坑。

    问题描述:

    程序跑起来,在调用某个xml配置的方法时,报找不到xml中配置方法的错误。

    问题原因:

    后来经过排查,才发现是因为我在项目中使用了mybatis-plus,而mybatis-plus中的MybatisPlusAutoConfiguration覆盖了mybatis的MybatisAutoConfiguration。

    解决办法:

    通过将application.properties中的

    mybatis.mapper-locations=classpath*:*Mapper.xml
    

    改为:

    mybatis-plus.mapper-locations=classpath*:*Mapper.xml
    

    问题解决!!!

    相关文章

      网友评论

          本文标题:在springboot中,mybatis同时使用注解和xml配置

          本文链接:https://www.haomeiwen.com/subject/ozjzzqtx.html