SpringBoot整合mybatis及注意事項
主要步驟
- 添加依賴 mybatis
- 在配置文件中配置數據源信息
- 編寫pojo mapper接口 mapeer映射文件
- 手動配置mybatis的包掃描
在主啟動類添加@MapperScan
1:導入依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2:配置數據源信息
在application.yml中進行配置
#DB Configation spring: datasource: driverClassName: com.mysql.jdbc.Driver //注意如果出現了無法連接數據庫問題,在tx后面添加 ?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
url: jdbc:mysql://127.0.0.1:3306/tx
username: root password: 813100 jpa: database: MySQL show-sql: true generate-ddl: true
3:書寫pojo實體類和對應的mapper接口及映射文件
pojo實體類
package com.offcn.springbootdemo1.pojo; public class UUser { private Integer id; private String username; private String password; private String name; //此處添加set,get,構造方法以及重寫toString
}
mapper接口
package com.offcn.springbootdemo1.mapper; import com.offcn.springbootdemo1.pojo.UUser; import java.util.List; public interface UUserMapper { List<UUser> selectUUser(); }
mapper映射文件
<?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.offcn.springbootdemo1.mapper.UUserMapper">
<select id="selectUUser" resultType="com.offcn.springbootdemo1.pojo.UUser"> select * from user </select>
</mapper>
注意:如果mapper接口和mapper映射文件放在同一個地方
那么在運行會出現錯誤
解決方案:
1:在resources目錄下建立一個和mapper接口相同的目錄結構,把mapper映射文件放進去
2:如果想把mapper接口和mapper映射文件放在一起
那么在pom.xml中添加如下配置
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include> <include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
4:手動配置mybatis掃描
在啟動類上添加注解@MapperScan
package com.offcn.springbootdemo1; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan(basePackages = "com.offcn.springbootdemo1.mapper") public class Springbootdemo1Application { public static void main(String[] args) { SpringApplication.run(Springbootdemo1Application.class, args); } }
5:在Controller中進行測試
package com.offcn.springbootdemo1.controller; //導包
@Controller public class UUserController { @Resource private UUserMapper userMapper; @RequestMapping("aa") @ResponseBody public List<UUser> selectUUser(){ List<UUser> uUsers = userMapper.selectUUser(); return uUsers; } }