看了很多人寫的博客,要么太復雜,要么沒有添加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
我的個人博客,一起進步~