美文网首页资料程序员Spring Boot
超简单,Spring boot 配置mybatis

超简单,Spring boot 配置mybatis

作者: 大都小酒馆 | 来源:发表于2016-12-28 11:02 被阅读1568次

    看了很多人写的博客,要么太复杂,要么没有添加xml的方式,自己亲自配置了一下,供各位参考

    项目截图
    image
    添加pom文件
     <!-- 设置mybatis -->
        <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>1.1.1</version>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>6.0.4</version>
        </dependency>
    
    添加Mapper类
    @Mapper
    public interface UserMapper {
        User findUserById(Integer id);
    }
    
    
    添加mapper.xml
    <?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.example.mapper.UserMapper">
    
        <resultMap id = "result" type = "com.example.domain.User">
            <result property = "id" column = "id"/>
            <result property = "name" column = "name"/>
        </resultMap>
        <select id = "findUserById" resultMap = "result">
            SELECT * FROM act_user where id = #{id};
        </select>
    </mapper>
    
    在application.properties添加数据库和mybatis配置
    # mysql
    spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    spring.datasource.username=root
    spring.datasource.password=root
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    # mybatis
    # 对应实体类的包名
    mybatis.typeAliasesPackage=com.example.domain
    # mapper.xml文件所在位置,我放到了resources下面
    mybatis.mapperLocations=classpath:**/mapper/*.xml
    
    配置启动类,添加MapperScan注解
    @SpringBootApplication
    @MapperScan("com.example.mapper")
    public class SpringBootDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootDemoApplication.class, args);
        }
    }
    
    
    添加日志输出,在logback-spring.xml中添加这一行即可
    <logger name="com.example.mapper" level="DEBUG"></logger>
    
    运行效果
    image

    欢迎访问我的博客,一起进步

    相关文章

      网友评论

      本文标题:超简单,Spring boot 配置mybatis

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