MyBatis-Plus整合Spring Demo
阿新 • • 發佈:2018-11-25
簡介
官方文件:苞米豆
MyBatis-Plus(簡稱MP)是一個 MyBatis 的增強工具,在 Mybatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
特性
- 無侵入:Mybatis-Plus 在 Mybatis 的基礎上進行擴充套件,只做增強不做改變,引入 Mybatis-Plus 不會對您現有的 Mybatis 構架產生任何影響,而且 MP 支援所有 Mybatis 原生的特性
- 依賴少:僅僅依賴 Mybatis 以及 Mybatis-Spring
- 損耗小:啟動即會自動注入基本CURD,效能基本無損耗,直接面向物件操作
- 預防Sql注入:內建Sql注入剝離器,有效預防Sql注入攻擊
- 通用CRUD操作:內建通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求
- 多種主鍵策略:支援多達4種主鍵策略(內含分散式唯一ID生成器),可自由配置,完美解決主鍵問題
- 支援ActiveRecord:支援 ActiveRecord 形式呼叫,實體類只需繼承 Model 類即可實現基本 CRUD 操作
- 支援程式碼生成:採用程式碼或者 Maven 外掛可快速生成 Mapper 、 Model 、 Service 、 Controller 層程式碼,支援模板引擎,更有超多自定義配置等您來使用(P.S. 比 Mybatis 官方的 Generator 更加強大!)
- 支援自定義全域性通用操作:支援全域性通用方法注入( Write once, use anywhere )
- 支援關鍵詞自動轉義:支援資料庫關鍵詞(order、key……)自動轉義,還可自定義關鍵詞
- 內建分頁外掛:基於Mybatis物理分頁,開發者無需關心具體操作,配置好外掛之後,寫分頁等同於普通List查詢
- 內建效能分析外掛:可輸出Sql語句以及其執行時間,建議開發測試時啟用該功能,能有效解決慢查詢
- 內建全域性攔截外掛:提供全表 delete 、 update 操作智慧分析阻斷,預防誤操作
整合MyBatis和MP的不同
1.依賴不同
整合MyBatis的依賴
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- MyBatis-Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
整合MP
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
2.SqlSession中的Bean的型別不同
MP中的class
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
MyBatis中的class
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBatis的配置的檔案 -->
<property name="configLocation" value="classpath:mybatis.xml"></property>
</bean>
構建專案Spring+MyBatis-Plus
專案下載:點選開啟連結
MP比MyBatis的優勢就是省去了mapper.xml,那麼問題來了,沒有mapper.xml怎麼有SQL和方法呢
這裡就是MP給實現的,注意看下面的dao層,就是繼承了一個介面BaseMapper<T>
專案結構
pom.mxl
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.imooc</groupId>
<artifactId>MyBatisPlus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
<!-- 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 日誌 -->
<!-- 實現slf4j介面並整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 資料庫 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- MyBatis <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId>
<version>3.4.1</version> </dependency> -->
<!-- MyBatis-Spring <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId>
<version>1.3.0</version> </dependency> -->
</dependencies>
</project>
spring配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置自動掃描的包,使其自動注入到IOC容器 -->
<context:component-scan base-package="com.imooc.service"></context:component-scan>
<!-- 匯入資原始檔 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置資料來源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 配置MyBatis的SqlSession -->
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBatis的配置的檔案 -->
<property name="configLocation" value="classpath:mybatis.xml"></property>
<!-- 別名處理 -->
<!-- <property name="typeAliasesPackage" value="com.imooc.entity"></property> -->
<!-- 注入MP的全域性策略配置 -->
<property name="globalConfig" ref="globalConfiguration"></property>
<!-- 外掛註冊 -->
<property name="plugins">
<list>
<!-- 註冊分頁外掛 -->
<bean class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"></bean>
<!-- 註冊效能分析外掛 -->
<bean class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">
<property name="format" value="true"></property>
<!-- <property name="maxTime" value="5"></property> -->
</bean>
</list>
</property>
</bean>
<!-- MP的全域性策略配置 -->
<bean id="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!--
在2.3版本以後,dbColumnUnderline 預設值就是true
駝峰命名轉換為下劃線命名 user_name對應userName
-->
<property name="dbColumnUnderline" value="true"></property>
<!--
全域性的主鍵策略
省去了@TableId(value = "id", type = IdType.AUTO)為主鍵策略
-->
<!-- <property name="idType" value="0"></property> -->
<!--
全域性的表字首策略配置
省略了@TableName("employee") ,如果你的表名為bt1_user
-->
<!-- <property name="tablePrefix" value="tbl_"></property> -->
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 自動掃描 com.imooc.dao下的interface,並加入IOC容器 -->
<property name="basePackage" value="com.imooc.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 開啟事務 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 可通過註解控制事務 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
MyBatis配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--
=====>設定別名: 將com.imooc.entity.User設定為User
如果不設定別名<select id="selectDemo" resultType="com.imooc.entity.User"> ***</select>
設定別名 <select id="selectDemo" resultType="User">***</select>
-->
<typeAliases>
<package name="com.imooc.entity"></package>
</typeAliases>
</configuration>
資料庫配置檔案
jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...
實體層
package com.imooc.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
/**
*
* @TableName("employee") 如果你資料的表和實體類的名稱不一樣,那就用tableName註解
*
*
*/
public class Employee {
@TableId(value = "id", type = IdType.AUTO)//value是對應資料庫欄位的名稱,type為主鍵策略
private Integer id;
//@TableField("emp_name")如果你的資料庫欄位和屬性名稱不匹配
private String name;
private String email;
private Integer gender;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Employee(String name, String email, Integer gender, Integer age) {
this.name = name;
this.email = email;
this.gender = gender;
this.age = age;
}
public Employee() {
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", email=" + email + ", gender=" + gender + ", age=" + age
+ "]";
}
}
Dao層
注意:僅僅繼承了BashMapper
package com.imooc.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.imooc.entity.Employee;
/**
* MyBatis-plus
* @author lenovo
*
*/
public interface EmployeeMapper extends BaseMapper<Employee>{
}
測試層
package com.imooc.main;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
System.out.println("----------------------");
System.out.println(context);
DataSource dataSource = (DataSource) context.getBean("dataSource");
System.out.println(dataSource);
System.out.println(dataSource.getConnection());
}
}
Mapper中繼承的BaseMapper的方法的使用
package com.imooc.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baomidou.mybatisplus.plugins.Page;
import com.imooc.dao.EmployeeMapper;
import com.imooc.entity.Employee;
public class EmployeeMapperTest {
private ClassPathXmlApplicationContext context = null;
private EmployeeMapper employeeDao = null;
// private UserMapper userDao=null;
@Before
public void before() {
context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
employeeDao = context.getBean(EmployeeMapper.class);
// userDao=context.getBean(UserMapper.class);
}
@Test
public void test() {
System.out.println(employeeDao);
}
/**
* 按照List中的id,返回刪除了幾條資料
*/
@Test
public void deleteBatchIds() {
List<Integer> ids=new ArrayList<>();
//ids.add(1);
ids.add(10);
ids.add(9);
Integer result=employeeDao.deleteBatchIds(ids);
System.out.println("刪除記錄數"+result);
}
/**
* 按照條件刪除,返回刪除了幾條資料
*/
@Test
public void deleteByMap() {
Map<String, Object> columnMap = new HashMap<>();
//columnMap.put("gender", 2);
columnMap.put("age", 11);
Integer result=employeeDao.deleteByMap(columnMap);
System.out.println("刪除記錄數"+result);
}
/*
* 返回是否刪除成功 1表示成功,0表示不成功
*/
@Test
public void deleteById() {
Integer result = employeeDao.deleteById(10);
System.out.println("刪除結果:" + (result != 0));
}
@Test
public void selectById() {
Employee e = employeeDao.selectById(1);
System.out.println(e);
}
/**
* 根據Employee中屬性的值查詢一個,一個,一個物件,如果返回多個,報錯,只能返回一個或者null 自我感覺這個方法不推薦
*/
@Test
public void selectOne() {
Employee e = new Employee();
e.setId(10);
e.setName("張三10");
e.setEmail("[email protected]");
e.setAge(13);
e.setGender(0);
Employee ee = employeeDao.selectOne(e);
System.out.println(ee);
}
/**
* 簡單的沒有查詢條件的分頁查詢 注意:效果不是很好,因為底層SQL為(SELECT id AS id,`name`,email,gender,age
* FROM employee ) page=new Page<>(current, size)
* employeeDao.selectPage(rowBounds, wrapper)
*/
@Test
public void selectPage() {
Page<Employee> page = new Page<>(2, 2);// currect,size
List<Employee> emps = employeeDao.selectPage(page, null);
System.out.println(emps);
}
/**
* 按照條件查詢
*/
@Test
public void selectByMap() {
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("gender", 1);
columnMap.put("age", 1);
List<Employee> employees = employeeDao.selectByMap(columnMap);
for (Employee employee : employees) {
System.out.println(employee);
}
}
/**
* SQL:SELECT id AS id,`name`,email,gender,age FROM employee WHERE id IN ( ?
* , ? , ? ) 查詢多個ID
*/
@Test
public void selectBatchIds() {
List<Integer> idList = new ArrayList<>();
idList.add(1);
idList.add(2);
idList.add(3);
List<Employee> employees = employeeDao.selectBatchIds(idList);
for (Employee employee : employees) {
System.out.println(employee);
}
}
@Test
public void update() {
Employee e = new Employee();
e.setId(10);
e.setName("張三10");
e.setEmail("[email protected]");
e.setAge(13);
e.setGender(0);
int result = employeeDao.updateById(e);// 更新屬性為非空的列
// int result = employeeDao.updateAllColumnById(e);//更新全部的列
System.out.println("處理結果:" + (result != 0));
System.out.println("返回的主鍵值:" + e.getId());
}
/**
* //e.setAge(13); 先判斷是否為空,不為空的屬性插入的表中 NSERT INTO employee ( `name`, email,
* gender, age ) VALUES ( ?, ?, ?, ? ) INSERT INTO employee ( `name`, email,
* gender ) VALUES ( ?, ?, ? )
*/
@Test
public void insert() {
Employee e = new Employee();
e.setName("張三");
e.setEmail("[email protected]");
e.setAge(13);
e.setGender(1);
int result = employeeDao.insert(e);
// employeeDao.insertAllColumn(e);講所有的屬性都插入,null也插入
System.out.println("處理結果:" + (result != 0));
System.out.println("返回的主鍵值:" + e.getId());
}
}
Condition條件構造器
package com.imooc.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.imooc.dao.EmployeeMapper;
import com.imooc.entity.Employee;
public class ConditionTest {
private ClassPathXmlApplicationContext context = null;
private EmployeeMapper employeeDao = null;
// private UserMapper userDao=null;
@Before
public void before() {
context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
employeeDao = context.getBean(EmployeeMapper.class);
// userDao=context.getBean(UserMapper.class);
}
@Test
public void test() {
System.out.println(employeeDao);
}
/**
* 和wrapper方法一樣
*/
@Test
public void conditionDemo() {
Condition condition=Condition.create();
condition.eq("gender", 1);
List<Employee>emps=null;
emps=employeeDao.selectList(condition);
System.out.println(emps);
}
}
EntityWrapper條件構造器
package com.imooc.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.imooc.dao.EmployeeMapper;
import com.imooc.entity.Employee;
public class WrapperTest {
private ClassPathXmlApplicationContext context = null;
private EmployeeMapper employeeDao = null;
// private UserMapper userDao=null;
@Before
public void before() {
context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
employeeDao = context.getBean(EmployeeMapper.class);
// userDao=context.getBean(UserMapper.class);
}
@Test
public void test() {
System.out.println(employeeDao);
}
@Test
public void selectList_EntityWrapper(){
EntityWrapper<Employee> wrapper=new EntityWrapper<>();
wrapper.eq("gender", 1)
//.or().like("email", "a") //WHERE (gender = ? OR email LIKE ?)
.orNew().like("email", "a");//WHERE (gender = ? ) OR (email LIKE ?)
List<Employee> emps=employeeDao.selectList(wrapper);
System.out.println(emps);
}
/**同上
* R
* U
* D
*/
//@Test
public void RUD_EntityWrapper(){
EntityWrapper<Employee> wrapper=new EntityWrapper<>();
Employee e=new Employee();
//e.setAge(1);修改的內容
employeeDao.update(e, wrapper);//按照wrapper條件修改為e中的內容
employeeDao.delete(wrapper);//刪除按照wrapper條件的資料
}
@Test
public void EntityWrapper(){
Page<Employee> page=new Page<>(1, 2);
EntityWrapper<Employee> wrapper=new EntityWrapper<>();
//wrapper.between(column, val1, val2) 注意:column是資料庫欄位,不是類的屬性
wrapper
//.between("age", 10, 20)//查詢age欄位在10-20之間的記錄
.eq("gender", 1);//查詢欄位為gender為1的記錄
List<Employee> emps=employeeDao.selectPage(page, wrapper);
System.out.println(emps);
}
}
分頁查詢
package com.imooc.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.imooc.dao.EmployeeMapper;
import com.imooc.entity.Employee;
public class PageTest {
private ClassPathXmlApplicationContext context = null;
private EmployeeMapper employeeDao = null;
// private UserMapper userDao=null;
@Before
public void before() {
context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
employeeDao = context.getBean(EmployeeMapper.class);
// userDao=context.getBean(UserMapper.class);
}
@Test
public void test() {
System.out.println(employeeDao);
}
@Test
public void pageTest() {
Page page = new Page<>(2, 2);
List<Employee> emps = employeeDao.selectPage(page, null);
System.out.println(emps);
System.out.println("===============獲取分頁相關的一些資訊======================");
System.out.println("總條數:" + page.getTotal());
System.out.println("當前頁碼: " + page.getCurrent());
System.out.println("總頁碼:" + page.getPages());
System.out.println("每頁顯示的條數:" + page.getSize());
System.out.println("是否有上一頁: " + page.hasPrevious());
System.out.println("是否有下一頁: " + page.hasNext());
// 將查詢的結果封裝到page物件中
page.setRecords(emps);
}
}