超简单,spring boot 添加mybatis


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

项目截图

 

1、添加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>

2、添加mapper类和mapper.xml

@Mapper
public interface UserMapper {
    User findUserById(Integer id);
}
<?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>

3、在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

4、配置启动类,添加MapperScan注解

@SpringBootApplication
@MapperScan("com.example.mapper")
public class SpringBootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

5、添加日志输出,在logback-spring.xml中添加这一行即可

<logger name="com.example.mapper" level="DEBUG"></logger>

6、最终效果,访问自己的Controller

 

 我的个人博客,一起进步~

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM