寫在前面:
這段時間太忙了,已經一週沒有更新了,抱歉抱歉。
順便多一嘴:這個其實還是學學思想,當成個工具就可以,在他之上還有個Mybatis-plus,這兩個好用的工具都僅僅是工具,不能過度依賴。
通用Mapper是國內的大神寫的一個mybatis外掛,裡面有很多的增刪改查方法,合理地(注意,一定要合理地)使用是可以優化程式碼。但是不能一味地為了不寫而不寫,這樣的開發是沒有意義的,借用原作者的一段話,希望大家可以明白:「通用 Mapper 的目的就是為了讓開發人員能偷懶,能把更多的時間用在重要的事情上,但是有一部分人在不該偷懶的地方也偷懶了。」我個人也是非常贊同這個觀點的,通用Mapper可以幫助我們去完成一些少量且繁瑣的sql語句,所以,它只需要提供少量必要的通用方法就夠了。
通用 Mapper4 是一個可以實現任意 MyBatis 通用方法的框架,專案提供了常規的增刪改查操作以及Example 相關的單表操作。通用 Mapper 是為了解決MyBatis 使用中 90% 的基本操作,使用它可以很方便的進行開發,可以節省開發人員大量的時間。
碼雲網址:通用Mapper
既然前面已經說過通用Mapper的一些侷限性了,那麼在不考慮這個侷限性的前提下,那這篇文章來說一下通用Mapper的優點:
既然這個工具類不是我寫的,那我也就不多廢話了,立刻上手教教大家如何入門,看完保證大家知道如果進行使用,但是一定要注意前面所說的合理地使用。
CREATE DATABASE db_testCHARACTER SET utf8;
USE db_test;
CREATE TABLE `t_user` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',
`username` VARCHAR(20) NOT NULL COMMENT '使用者名稱',
`password` VARCHAR(20) NOT NULL COMMENT '密碼',
`name` VARCHAR(30) DEFAULT NULL COMMENT '姓名',
`age` INT(11) DEFAULT NULL COMMENT '年齡',
`telephone` VARCHAR(15) DEFAULT NULL COMMENT '手機號',
`email` VARCHAR(50) DEFAULT NULL COMMENT '郵箱',
PRIMARY KEY (`id`)
) ENGINE = INNODB AUTO_INCREMENT = 8 CHARSET = utf8;
INSERT INTO `t_user`
VALUES ('1', 'AAA', 'AAA111', '阿大', '25', '18211111111', 'NO.1@163.com');
INSERT INTO `t_user`
VALUES ('2', 'BBB', 'BBB222', '阿二', '24', '18222222222', 'NO.2@163.com');
INSERT INTO `t_user`
VALUES ('4', 'DDD', 'DDD444', '阿四', '22', '18244444444', 'NO.4@163.com');
INSERT INTO `t_user`
VALUES ('5', 'EEE', 'EEE555', '阿五', '21', '18255555555', 'NO.5@163.com');
INSERT INTO `t_user`
VALUES ('7', 'GGG', 'GGG777', '阿七', '19', '18277777777', 'NO.7@163.com');
這裡指定一下自增從8開始,模擬資料庫
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.g55zhw</groupId>
<artifactId>mapperdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mapperdemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<!--排除spring-boot-starter-logging紀錄檔依賴,使用lf4j-log4j12紀錄檔依賴-->
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--springboot整合通用mapper依賴-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<!--lombok依賴包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--lf4j-log4j12依賴,方便查詢執行的sql語句-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!--pageHelper依賴-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
application.properties
# 設定應用的名稱
spring.application.name = mapperdemo
#資料庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#資料庫存取路徑
spring.datasource.url=jdbc:mysql://192.168.126.129/db_test
#使用Unicode字元集
useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
#使用者名稱
spring.datasource.username=root
#密碼
spring.datasource.password=root
#pagehelper分頁外掛設定
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
package com.g55zhw.mapperdemo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
// lombok : 簡化實體類的編寫,可以省略實體的建構函式、屬性的set和get方法
// lombok用法:1.引入依賴;2.idea安裝lombok外掛;3.實體類中使用註解
/**
* com.g55zhw.mapperdemo.pojo
*
* @author g55zhw
* @create 2020-10-18-11-58
*/
@Data //生成get/set方法
@NoArgsConstructor //生成一個無引數的構造方法
@AllArgsConstructor //生成一個包含所有變數的構造方法
@Table(name="t_user")
public class User {
@Id 資料庫表中的id主鍵和實體類id屬性的對映關係
@KeySql(useGeneratedKeys = true)//在增加資料之後,獲取增加資料的id,填充到實體類id屬性
private Long id;
@Column(name = "username") //實體類的userName屬性,對應資料庫表中的user_name欄位
private String userName;
private String password;
private String name;
private Integer age;
private String telephone;
private String email;
}
package com.g55zhw.mapperdemo.mapper;
import com.g55zhw.mapperdemo.pojo.User;
import tk.mybatis.mapper.common.Mapper;
/**
* com.g55zhw.mapperdemo.pojo
*
* mapper介面
* 如果要實現基本的增、刪、改、查等,需要繼承BaseMapper
* 如果要實現條件查詢等,需要繼承Mapper
* 泛型表示mapper操作哪個實體類及實體類對應的表
*
* @author g55zhw
* @create 2020-10-18-12-01
*/
public interface UserMapper extends Mapper<User> {
}
<?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.g55zhw.mapperdemo.mapper.UserMapper">
</mapper>
package com.g55zhw.mapperdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
/**
* com.g55zhw.mapperdemo.pojo
*
* @author g55zhw
* @create 2020-10-18-12-04
*/
@MapperScan("com.g55zhw.mapperdemo.mapper")
@SpringBootApplication
public class MapperdemoApplication {
public static void main(String[] args) {
SpringApplication.run(MapperdemoApplication.class, args);
}
}
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 tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;
/**
* com.g55zhw.mapperdemo.pojo
*
* @author g55zhw
* @create 2020-10-18-12-08
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperdemoApplicationTests {
@Autowired
private UserMapper userMapper;
//根據id查詢資料
@Test
public void contextLoads() {
}
//新增使用者
@Test
public void insertTest() {
}
//更新使用者
@Test
public void updateTest() {
}
//刪除使用者
@Test
public void deleteTest() {
}
//根據主鍵查詢使用者
@Test
public void selectTest() {
}
//查詢全部使用者
@Test
public void selectAllTest() {
}
//條件查詢
@Test
public void selectByTest() {
}
//分頁查詢
@Test
public void selectPageTest() {
}
}
程式碼演示
@Test
public void insertTest() {
User user = new User();
user.setName("阿八");
user.setAge(18);
user.setEmail("NO.8@163.com");
user.setTelephone("18288888888");
user.setUserName("HHH");
user.setPassword("HHH888");
int result = userMapper.insert(user);
System.out.println("result="+result);
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.insert]-[DEBUG] ==> Preparing: INSERT INTO t_user ( id,username,password,name,age,telephone,email ) VALUES( ?,?,?,?,?,?,? )
......
result=1
程式碼演示
@Test
public void deleteTest() {
int result = userMapper.deleteByPrimaryKey(11);
System.out.println("result="+result);
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.deleteByPrimaryKey]-[DEBUG] ==> Preparing: DELETE FROM t_user WHERE id = ?
......
result=0
程式碼演示
@Test
public void deleteTest() {
int result = userMapper.deleteByPrimaryKey(11);
System.out.println("result="+result);
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.deleteByPrimaryKey]-[DEBUG] ==> Preparing: DELETE FROM t_user WHERE id = ?
......
result=1
程式碼演示
@Test
public void updateTest() {
User user = new User();
user.setId(2L);
user.setName("阿二想做老大");
user.setAge(25);
//int result = userMapper.updateByPrimaryKey(user);
//updateByPrimaryKeySelective會對欄位進行判斷再更新(如果為Null就忽略更新),如果你只想更新某一欄位,可以用這個方法;
//updateByPrimaryKey對你注入的欄位全部更新
int result = userMapper.updateByPrimaryKeySelective(user);
System.out.println("result="+result);
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.deleteByPrimaryKey]-[DEBUG] ==> Preparing: DELETE FROM t_user WHERE id = ?
......
result=1
程式碼演示
@Test
public void contextLoads() {
User user = userMapper.selectByPrimaryKey(5);
System.out.println(user);
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByPrimaryKey]-[DEBUG] ==> Preparing: SELECT id,username,password,name,age,telephone,email FROM t_user WHERE id = ?
......
User(id=5, userName=EEE, password=EEE555, name=阿五, age=21, telephone=18255555555, email=NO.5@163.com)
程式碼演示
@Test
public void selectAllTest() {
List<User> users = userMapper.selectAll();
for (User user : users){
System.out.println(user);
}
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==> Preparing: SELECT id,username,password,name,age,telephone,email FROM t_user
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==> Parameters:
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] <== Total: 5
......
User(id=1, userName=AAA, password=AAA111, name=阿大, age=25, telephone=18211111111, email=NO.1@163.com)
User(id=2, userName=BBB, password=BBB222, name=阿二想做老大, age=25, telephone=18222222222, email=NO.2@163.com)
User(id=5, userName=EEE, password=EEE555, name=阿五, age=21, telephone=18255555555, email=NO.5@163.com)
User(id=7, userName=GGG, password=GGG777, name=阿七, age=19, telephone=18277777777, email=NO.7@163.com)
User(id=8, userName=HHH, password=HHH888, name=阿八, age=18, telephone=18288888888, email=NO.8@163.com)
程式碼演示
@Test
public void selectByTest() {
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
//查詢「age」小於「20」的物件
criteria.andLessThanOrEqualTo("age",20);
List<User> users = userMapper.selectByExample(example);
for (User user : users){
System.out.println(user);
}
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByExample]-[DEBUG] ==> Preparing: SELECT id,username,password,name,age,telephone,email FROM t_user WHERE ( ( age <= ? ) )
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByExample]-[DEBUG] ==> Parameters: 20(Integer)
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByExample]-[DEBUG] <== Total: 2
......
User(id=7, userName=GGG, password=GGG777, name=阿七, age=19, telephone=18277777777, email=NO.7@163.com)
User(id=8, userName=HHH, password=HHH888, name=阿八, age=18, telephone=18288888888, email=NO.8@163.com)
程式碼演示
@Test
@Test
public void selectPageTest() {
//顯示示第一頁,每頁三條,按age升序
PageHelper.startPage(1,3,"age asc");
List<User> users = userMapper.selectAll();
for (User user:users){
System.out.println(user);
}
}
執行結果
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll_COUNT]-[DEBUG] ==> Preparing: SELECT count(0) FROM t_user
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll_COUNT]-[DEBUG] ==> Parameters:
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll_COUNT]-[DEBUG] <== Total: 1
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==> Preparing: SELECT id, username, password, name, age, telephone, email FROM t_user order by age asc LIMIT ?
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==> Parameters: 3(Integer)
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] <== Total: 3
......
User(id=8, userName=HHH, password=HHH888, name=阿八, age=18, telephone=18288888888, email=NO.8@163.com)
User(id=7, userName=GGG, password=GGG777, name=阿七, age=19, telephone=18277777777, email=NO.7@163.com)
User(id=5, userName=EEE, password=EEE555, name=阿五, age=21, telephone=18255555555, email=NO.5@163.com)