當(dāng)前位置:首頁(yè) > IT技術(shù) > 移動(dòng)平臺(tái) > 正文

Spring boot集成 MyBatis 通用Mapper
2021-10-11 14:58:07

Spring boot集成 MyBatis 通用Mapper

配置

POM文件

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath />
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

?

同一環(huán)境1.5.7.RELEASE版本的Spring-boot會(huì)拋Caused by: java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver異常,1.5.6.RELEASE以及1.5.5.RELEASE版本親測(cè)沒(méi)問(wèn)題



application.properties配置文件

#數(shù)據(jù)庫(kù)
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=741852
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#mybatis&&通用Mapper
mybatis.type-aliases-package=com.karle.bean
mybatis.mapper-locations=classpath:mapper/*.xml
mapper.mappers=com.karle.tk.TkMapper
mapper.identity=MYSQL

#分頁(yè)插件
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

#log
logging.file=logger.log
logging.level.*=debug

?

映射實(shí)體(省略字段get、set)

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

/**
* 名稱
*/
@Column(name = "name")
private String name;

/**
* 年齡
*/
@Column(name = "age")
private Integer age;

/**
* 身份編號(hào)
*/
@Column(name = "card_no")
private Integer cardNo;

/**
* 生日
*/
@Column(name = "birthday")
private Date birthday;
}

?

本地通用Mapper接口(繼承通用Mapper接口)

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface TkMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

?

Mapper接口:基本的增、刪、改、查方法?

MySqlMapper:針對(duì)MySQL的額外補(bǔ)充接口,支持批量插入

業(yè)務(wù)接口(繼承“本地通用Mapper接口”)

import org.apache.ibatis.annotations.Param;

import com.karle.bean.User;
import com.karle.tk.TkMapper;

public interface UserMapper extends TkMapper<User> {

public User selectByCardNo(@Param("cardNo") int cardNo);

}

?

Spring-boot啟動(dòng)類,@MapperScan僅掃描業(yè)務(wù)接口包,不能掃描本地通用Mapper接口包,否則報(bào)java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class異常

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = { "com.karle.mapper" })
public class SpringBootMyBatisApplication {

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

}

?

通過(guò)使用@MapperScan可以指定要掃描的Mapper類的包的路徑,比如:

Java代碼??

  1. @SpringBootApplication??
  2. @MapperScan("com.kfit.*.mapper")??
  3. public?class?App?{??
  4. ????public?static?void?main(String[]?args)?{??
  5. ???????SpringApplication.run(App.class,?args);??
  6. ????}??
  7. }??

?

或者:

Java代碼??

  1. @SpringBootApplication??
  2. @MapperScan("com.kfit.mapper")??
  3. public?class?App?{??
  4. ????public?static?void?main(String[]?args)?{??
  5. ???????SpringApplication.run(App.class,?args);??
  6. ????}??
  7. }??

?

???????可以根據(jù)包的結(jié)構(gòu)指定不同的表達(dá)式。

?

使用@MapperScan注解多個(gè)包

可以使用如下的方式指定多個(gè)包:

Java代碼??

  1. @SpringBootApplication??
  2. @MapperScan({"com.kfit.demo","com.kfit.user"})??
  3. public?class?App?{??
  4. ????public?static?void?main(String[]?args)?{??
  5. ???????SpringApplication.run(App.class,?args);??
  6. ????}??
  7. }??

?

???????如果mapper類沒(méi)有在Spring Boot主程序可以掃描的包或者子包下面,可以使用如下方式進(jìn)行配置:

Java代碼??

  1. @SpringBootApplication??
  2. @MapperScan({"com.kfit.*.mapper","org.kfit.*.mapper"})??
  3. public?class?App?{??
  4. ????public?static?void?main(String[]?args)?{??
  5. ???????SpringApplication.run(App.class,?args);??
  6. ????}??
  7. } ?
  8. ?

單元測(cè)試


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.github.pagehelper.PageHelper;
import com.karle.bean.User;
import com.karle.mapper.UserMapper;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMyBatisApplicationTests {

@Autowired
private UserMapper mapper;

// 插入一條新記錄
@Test
public void insertOne() {
User newUser = new User();
int cardNo = (int) (Math.random() * 10000000);
newUser.setAge(24);
newUser.setBirthday(new Date());
newUser.setName(cardNo + "用戶");
newUser.setCardNo(cardNo);
mapper.insertSelective(newUser);
System.out.println("插入成功");
}

// 批量插入記錄
@Test
public void insertMore() {
List<User> recordList = new ArrayList<User>();
for (int i = 0; i < 2; i++) {
User newUser = new User();
int cardNo = (int) (Math.random() * 10000000);
newUser.setAge(26);
newUser.setBirthday(new Date());
newUser.setName(cardNo + "批量插入用戶");
newUser.setCardNo(cardNo);
recordList.add(newUser);
}
mapper.insertList(recordList);
System.out.println("批量插入成功");
}

// 根據(jù)唯一編號(hào)查詢用戶(通用Mapper查詢)
@Test
public void selectByCardNo() {
User paramBean = new User();
paramBean.setCardNo(6647403);
User dbUser = mapper.selectOne(paramBean);
if (dbUser != null) {
System.out.println("數(shù)據(jù)庫(kù)用戶(通用Mapper查詢):" + dbUser.getName());
return;
}
System.out.println("查無(wú)此用戶");
}

// 根據(jù)唯一編號(hào)查詢用戶(XML查詢)
@Test
public void selectByCardNoByXml() {
User dbUser = mapper.selectByCardNo(6105967);
if (dbUser != null) {
System.out.println("數(shù)據(jù)庫(kù)用戶(XML查詢):" + dbUser.getName());
return;
}
System.out.println("查無(wú)此用戶");
}

// 根據(jù)年齡查詢一組用戶
@Test
public void selectByAge() {
User paramBean = new User();
paramBean.setAge(24);
List<User> dbUserList = mapper.select(paramBean);
System.out.println("總共查詢數(shù):" + dbUserList.size());
}

// 分頁(yè)查詢用戶
@Test
public void selectByPage() {
PageHelper.offsetPage(1, 5);
List<User> dbUserList = mapper.select(null);
for (User item : dbUserList) {
System.out.println("分頁(yè)用戶:" + item.getName());
}
}

// 更新用戶信息
@Test
public void updateOneInfo() {
User paramBean = new User();
paramBean.setId(1);
paramBean.setAge(26);
mapper.updateByPrimaryKeySelective(paramBean);
System.out.println("更新成功");
}

}

事物的使用

spring Boot 使用事務(wù)非常簡(jiǎn)單,首先使用注解???@EnableTransactionManagement??開(kāi)啟事務(wù)支持后,然后在訪問(wèn)數(shù)據(jù)庫(kù)的Service方法上添加注解???@Transactional???便可。

??@EnableTransactionManagement??放在啟動(dòng)類上

本文摘自 :https://blog.51cto.com/u

開(kāi)通會(huì)員,享受整站包年服務(wù)立即開(kāi)通 >