SpringBootのMyBatisの統合と注意事項
主な手順
- MyBatisのを頼りに追加
- コンフィギュレーション・ファイルのソース情報でコンフィギュレーション・データ
- POJOマッパーインタフェースmapeerマッピングファイルを書きます
- 手動設定、パッケージスキャンMyBatisの
メインの起動クラスを@MapperScan追加
1:輸入依存関係
<依存性>
<のgroupId> org.mybatis.spring.boot </のgroupId>
<たartifactId> MyBatisのスプリングブートスタータ</たartifactId>
<バージョン> 1.1.1 </バージョン>
</依存>
2:構成データソース情報
設定application.ymlで
Configation #DB
春:
データソース:
driverClassName:はcom.mysql.jdbc.Driver
// データベースに接続できない問題がある場合は、= trueに戻って追加&characterEncoding useUnicode TX = UTF-8&useSslオプション= falseをserverTimezone = GMT&ことに注意してください?
URL:JDBC:MySQLの:/ / 127.0.0.1:3306/tx
ユーザ名:ルート
パスワード: 813100
JPA:
データベース:MySQLの
ショーは -sql:trueに
生成 -ddl:trueに
3:POJOエンティティクラスと対応するインターフェースとマッパーマッピングファイルを書きます
POJOエンティティクラス
パッケージcom.offcn.springbootdemo1.pojo;
パブリック クラスUUser {
プライベート整数ID;
プライベート文字列名;
プライベート文字列のパスワード;
プライベート文字列名;
//が設定ここで追加、取得、およびコンストラクタのtoStringを書き換えます
}
マッパーインタフェース
パッケージcom.offcn.springbootdemo1.mapper。
輸入com.offcn.springbootdemo1.pojo.UUser。
輸入はjava.util.List;
パブリック インターフェースUUserMapper {
リスト <UUser> selectUUser();
}
マッパーマッピングファイル
<?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;
}
}