学之前要有Mybatis ,Spring ,Maven的知识积累
难度3
MyBatis Plus
MyBatis-Plus(简称 MP),是一个 MyBatis 的增强工具包,只做增强不做改变. 为简化开
发工作、提高生产率而生
代码及文档发布地址
官方地址:
http://mp.baomidou.com
代码发布地址:
Github: https://github.com/baomidou/mybatis-plus
Gitee: https://gitee.com/baomidou/mybatis-plus
文档发布地址:
http://mp.baomidou.com/#/?id=%E7%AE%80%E4%BB%8B
一:mp1:通用 CRUD,条件构造器 EntityWrapper,目录
Employee.java
package com.atguigu.mp.beans;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
/**
* javaBean
*
* 定义JavaBean中成员变量时所使用的类型:
* 因为每个基本类型都有一个默认值:
* int ==> 0
* boolean ==> false
*
*/
/*
* MybatisPlus会默认使用实体类的类名到数据中找对应的表.
*
*/
//@TableName(value="tbl_employee")
public class Employee {
/*
* @TableId:
* value: 指定表中的主键列的列名, 如果实体属性名与列名一致,可以省略不指定.
* type: 指定主键策略.
*/
//@TableId(value="id" , type =IdType.AUTO)
private Integer id ; // int
@TableField(value = "last_name")
private String lastName;
private String email ;
private Integer gender;
private Integer age ;
@TableField(exist=false)
private Double salary ;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", age="
+ age + "]";
}
}
EmployeeMapper.java
package com.atguigu.mp.mapper;
import com.atguigu.mp.beans.Employee;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* Mapper接口
*
* 基于Mybatis: 在Mapper接口中编写CRUD相关的方法 提供Mapper接口所对应的SQL映射文件 以及 方法对应的SQL语句.
*
* 基于MP: 让XxxMapper接口继承 BaseMapper接口即可.
* BaseMapper<T> : 泛型指定的就是当前Mapper接口所操作的实体类类型
*
*/
public interface EmployeeMapper extends BaseMapper<Employee> {
// Integer insertEmployee(Employee employee );
// <insert useGeneratedKeys="true" keyProperty="id" > SQL...</insert>
}
applicationContext.xml
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务管理器 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于注解的事务管理 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!-- 配置SqlSessionFactoryBean
Mybatis提供的: org.mybatis.spring.SqlSessionFactoryBean
MP提供的:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
-->
<bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 别名处理 -->
<property name="typeAliasesPackage" value="com.atguigu.mp.beans"></property>
<!-- 注入全局MP策略配置 -->
<property name="globalConfig" ref="globalConfiguration"></property>
</bean>
<!-- 定义MybatisPlus的全局策略配置-->
<bean id ="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!-- 在2.3版本以后,dbColumnUnderline 默认值就是true -->
<property name="dbColumnUnderline" value="true"></property>
<!-- 全局的主键策略 -->
<property name="idType" value="0"></property>
<!-- 全局的表前缀策略配置 -->
<property name="tablePrefix" value="tbl_"></property>
</bean>
<!--
配置mybatis 扫描mapper接口的路径
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.atguigu.mp.mapper"></property>
</bean>
</beans>
log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
mybatis-config.xml
<?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>
</configuration>
TestMP.java
package com.atguigu.mp.test;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.atguigu.mp.beans.Employee;
import com.atguigu.mp.mapper.EmployeeMapper;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
public class TestMP {
private ApplicationContext ioc =
new ClassPathXmlApplicationContext("applicationContext.xml");
private EmployeeMapper employeeMapper =
ioc.getBean("employeeMapper",EmployeeMapper.class);
/**
* 条件构造器 删除操作
*/
@Test
public void testEntityWrapperDelete() {
employeeMapper.delete(
new EntityWrapper<Employee>()
.eq("last_name", "Tom")
.eq("age", 22)
);
}
/**
* 条件构造器 修改操作
*/
@Test
public void testEntityWrapperUpdate() {
Employee employee = new Employee();
employee.setLastName("苍老师");
employee.setEmail("cls@sina.com");
employee.setGender(0);
employeeMapper.update(employee,
new EntityWrapper<Employee>()
.eq("last_name", "Tom")
.eq("age", 44)
);
}
/**
* 条件构造器 查询操作
*/
@Test
public void testEntityWrapperSelect() {
//我们需要分页查询tbl_employee表中,年龄在18~50之间且性别为男且姓名为Tom的所有用户
// List<Employee> emps =employeeMapper.selectPage(new Page<Employee>(1, 2),
// new EntityWrapper<Employee>()
// .between("age", 18, 50)
// .eq("gender", 1)
// .eq("last_name", "Tom")
// );
// System.out.println(emps);
List<Employee > emps = employeeMapper.selectPage(
new Page<Employee>(1,2),
Condition.create()
.between("age", 18, 50)
.eq("gender", "1")
.eq("last_name", "Tom")
);
System.out.println(emps);
// 查询tbl_employee表中, 性别为女并且名字中带有"老师" 或者 邮箱中带有"a"
// List<Employee> emps = employeeMapper.selectList(
// new EntityWrapper<Employee>()
// .eq("gender", 0)
// .like("last_name", "老师")
// //.or() // SQL: (gender = ? AND last_name LIKE ? OR email LIKE ?)
// .orNew() // SQL: (gender = ? AND last_name LIKE ?) OR (email LIKE ?)
// .like("email", "a")
// );
// System.out.println(emps);
// 查询性别为女的, 根据age进行排序(asc/desc), 简单分页
// List<Employee> emps = employeeMapper.selectList(
// new EntityWrapper<Employee>()
// .eq("gender", 0)
// .orderBy("age")
// //.orderDesc(Arrays.asList(new String [] {"age"}))
// .last("desc limit 1,3")
// );
// System.out.println(emps);
}
/**
* 以上是《条件构造器》的一些案例
*/
/**
* 通用 删除操作
*/
@Test
public void testCommonDelete() {
//1 .根据id进行删除
Integer result = employeeMapper.deleteById(13);
System.out.println("result: " + result );
//2. 根据 条件进行删除
// Map<String,Object> columnMap = new HashMap<>();
// columnMap.put("last_name", "MP");
// columnMap.put("email", "mp@atguigu.com");
// Integer result = employeeMapper.deleteByMap(columnMap);
// System.out.println("result: " + result );
//3. 批量删除
// List<Integer> idList = new ArrayList<>();
// idList.add(3);
// idList.add(4);
// idList.add(5);
// Integer result = employeeMapper.deleteBatchIds(idList);
// System.out.println("result: " + result );
}
/**
* 通用 查询操作
*/
@Test
public void testCommonSelect() {
//1. 通过id查询
// Employee employee = employeeMapper.selectById(7);
// System.out.println(employee);
//2. 通过多个列进行查询 id + lastName
// Employee employee = new Employee();
// //employee.setId(7);
// employee.setLastName("小泽老师");
// employee.setGender(0);
//
// Employee result = employeeMapper.selectOne(employee);
// System.out.println("result: " +result );
//3. 通过多个id进行查询 <foreach>
// List<Integer> idList = new ArrayList<>();
// idList.add(4);
// idList.add(5);
// idList.add(6);
// idList.add(7);
// List<Employee> emps = employeeMapper.selectBatchIds(idList);
// System.out.println(emps);
//4. 通过Map封装条件查询
// Map<String,Object> columnMap = new HashMap<>();
// columnMap.put("last_name", "Tom");//注意这里是数据库的列名!!!!
// columnMap.put("gender", 1);
//
// List<Employee> emps = employeeMapper.selectByMap(columnMap);
// System.out.println(emps);
//5. 分页查询
List<Employee> emps = employeeMapper.selectPage(new Page<>(3, 2), null);
System.out.println(emps);
}
/**
* 通用 更新操作
*/
@Test
public void testCommonUpdate() {
//初始化修改对象
Employee employee = new Employee();
employee.setId(7);
employee.setLastName("小泽老师");
employee.setEmail("xz@sina.com");
employee.setGender(0);
//employee.setAge(33);
//Integer result = employeeMapper.updateById(employee);
Integer result = employeeMapper.updateAllColumnById(employee);
System.out.println("result: " + result );
}
/**
* 通用 插入操作
*/
@Test
public void testCommonInsert() {
//初始化Employee对象
Employee employee = new Employee();
employee.setLastName("MP");
employee.setEmail("mp@atguigu.com");
//employee.setGender(1);
//employee.setAge(22);
employee.setSalary(20000.0);
//插入到数据库
// insert方法在插入时, 会根据实体类的每个属性进行非空判断,只有非空的属性对应的字段才会出现到SQL语句中
//Integer result = employeeMapper.insert(employee);
//insertAllColumn方法在插入时, 不管属性是否非空, 属性所对应的字段都会出现到SQL语句中.
Integer result = employeeMapper.insertAllColumn(employee);
System.out.println("result: " + result );
//获取当前数据在数据库中的主键值
Integer key = employee.getId();
System.out.println("key:" + key );
}
@Test
public void testDataSource() throws Exception {
DataSource ds = ioc.getBean("dataSource",DataSource.class);
System.out.println(ds);
Connection conn = ds.getConnection();
System.out.println(conn);
}
}
pom.xml
<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.atguigu.mp</groupId>
<artifactId>mp01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- mp依赖
mybatisPlus 会自动的维护Mybatis 以及MyBatis-spring相关的依赖
-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
<!--junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
</dependencies>
</project>
理论知识:
创建测试表
-- 创建库
CREATE DATABASE mp;
-- 使用库
USE mp;
-- 创建表
CREATE TABLE tbl_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(50),
email VARCHAR(50),
gender CHAR(1),
age int
);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Tom','tom@atguigu.com',1,22);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Jerry','jerry@atguigu.com',0,25);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Black','black@atguigu.com',1,30);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('White','white@atguigu.com',0,35);
创建 javaBean
public class Employee {
private Integer id ;
private String lastName;
private String email ;
private Integer gender ;
private Integer age ;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email
+ ", gender=" + gender + ", age="
+ age + "]";
}
依赖配置
1) 在 pom.xml 中加入对 MP、Spring、连接池、Junit、Mysql 驱动等依赖
<!-- mp 依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
<!--junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
特别说明: Mybatis 及 Mybatis-Spring 依赖请勿加入项目配置,以免引起版本冲突!!!
Mybatis-Plus 会自动帮你维护!
2)
加入 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>
</configuration>
3)
加入 log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd
HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
4)
加入 db.properties 连接信息配置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mp
jdbc.username=root
jdbc.password=1234
5)
加入 spring 的配置文件 applicationContext.xml
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务管理器 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于注解的事务管理 -->
<tx:annotation-driven
transaction-manager="dataSourceTransactionManager"/>
<!-- 配置 SqlSessionFactoryBean -->
<bean id="sqlSessionFactoryBean"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<property
value="classpath:mybatis-config.xml"></property>
<!-- 别名处理 -->
<property name="typeAliasesPackage"
value="com.atguigu.mp.beans"></property>
</bean>
<!--
配置 mybatis 扫描 mapper 接口的路径
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage"
value="com.atguigu.mp.mapper"></property>
</bean>
</beans>
测试
1) 测试 Spring-Mybatis 的环境,保证 OK。
private ApplicationContext iocContext = new
ClassPathXmlApplicationContext("applicationContext.xml");
@Test
public void testEnvironment() throws Exception{
DataSource ds = iocContext.getBean("dataSource",DataSource.class);
Connection conn = ds.getConnection();
System.out.println(conn);
}
集成 MP
1) Mybatis-Plus 的集成非常简单,对于 Spring,我们仅仅需要把 Mybatis 自带的
MybatisSqlSessionFactoryBean 替换为 MP 自带的即可。
2)
<bean id="sqlSessionFactoryBean"
class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation"
value="classpath:mybatis-config.xml"></property>
<!-- 别名处理 -->
<property name="typeAliasesPackage"
value="com.atguigu.mp.beans"></property>
</bean>
3.1 通用 CRUD
1) 提出问题:
假设我们已存在一张 tbl_employee 表,且已有对应的实体类 Employee,实现
tbl_employee 表的 CRUD 操作我们需要做什么呢?
2) 实现方式:
基于 Mybatis
需要编写 EmployeeMapper 接口,并手动编写 CRUD 方法
提供 EmployeeMapper.xml 映射文件,并手动编写每个方法对应的 SQL 语句.
基于 MP
只需要创建 EmployeeMapper 接口, 并继承 BaseMapper 接口.这就是使用 MP
需要完成的所有操作,甚至不需要创建 SQL 映射文件。
3.2 插入操作
1) Integer insert(T entity);
2) @TableName
3) 全局的 MP 配置: <property name="tablePrefix" value="tbl_"></property>
4) @TableField
5) 全局的 MP 配置: <property name="dbColumnUnderline" value="true"></property>
6) @TableId
7) 全局的 MP 配置: <property name="idType" value="0"></property>
8) 支持主键自增的数据库插入数据获取主键值
Mybatis: 需要通过 useGeneratedKeys 以及 keyProperty 来设置
MP: 自动将主键值回写到实体类中
9) Integer insertAllColumn(T entity)
3.3 更新操作
1) Integer updateById(@Param("et") T entity);
2) Integer updateAllColumnById(@Param("et") T entity)
3.4 查询操作
1) T selectById(Serializable id);
2) T selectOne(@Param("ew") T entity);
3) List<T> selectBatchIds(List<? extends Serializable> idList);
4) List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
5) List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
3.5 删除操作
1) Integer deleteById(Serializable id);
2) Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);
3) Integer deleteBatchIds(List<? extends Serializable> idList);
3.6 MP 启动注入 SQL 原理分析
1) 问题: xxxMapper 继承了 BaseMapper<T>, BaseMapper 中提供了通用的 CRUD 方法,
方法来源于 BaseMapper, 有方法就必须有 SQL, 因为 MyBatis 最终还是需要通过
SQL 语句操作数据.
前置知识:MyBatis 源码中比较重要的一些对象, MyBatis 框架的执行流程
Configuration
MappedStatement
……..
2) 通过现象看到本质
A. employeeMapper 的本质 org.apache.ibatis.binding.MapperProxy
B. MapperProxy 中 sqlSession –>SqlSessionFactory
条件构造器 EntityWrapper
4.1 EntityWrapper 简介
1) Mybatis-Plus 通过 EntityWrapper(简称 EW,MP 封装的一个查询条件构造器)或者
Condition(与 EW 类似) 来让用户自由的构建查询条件,简单便捷,没有额外的负担, 能够有效提高开发效率
2) 实体包装器,主要用于处理 sql 拼接,排序,实体参数查询等
3) 注意: 使用的是数据库字段,不是 Java 属性!
4) 条件参数说
4.2,使用 EntityWrapper 的方式打开如上需求:
List<Employee> userList = employeeMapper.selectPage(
new Page<Employee>(2, 3),
new EntityWrapper<Employee>().eq("last_name",
"MybatisPlus")
.eq("gender", 1)
.between("age", 18, 50)
);
4.3 带条件的查询
1) List<T> selectList(@Param("ew") Wrapper<T> wrapper);
4.4 带条件的修改
1) Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper);
4.5 带条件的删除
1) Integer delete(@Param("ew") Wrapper<T> wrapper);
4.6 使用 Condition 的方式打开如上需求
List<Employee> userListCondition = employeeMapper.selectPage(
new Page<Employee>(2,3),
Condition.create().
eq("gender", 1).
eq("last_name", "MyBatisPlus").
between("age", 18, 50));
4.7 小结
MP: EntityWrapper Condition 条件构造器
MyBatis MBG : xxxExample→Criteria : QBC( Query By Criteria)
二:mp2:ActiveRecord(活动记录)
目录
Employee.java
package com.atguigu.mp.beans;
import java.io.Serializable;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
/**
* javaBean
*
* 定义JavaBean中成员变量时所使用的类型:
* 因为每个基本类型都有一个默认值:
* int ==> 0
* boolean ==> false
*
*/
/*
* MybatisPlus会默认使用实体类的类名到数据中找对应的表.
*
*/
public class Employee extends Model<Employee> {
private Integer id ; // int
private String lastName;
private String email ;
private Integer gender;
private Integer age ;
@TableField(exist=false)
private Double salary ;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", age="
+ age + "]";
}
/**
* 指定当前实体类的主键属性
*/
@Override
protected Serializable pkVal() {
return id;
}
}
EmployeeMapper.java
package com.atguigu.mp.mapper;
import com.atguigu.mp.beans.Employee;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* Mapper接口
*
* 基于Mybatis: 在Mapper接口中编写CRUD相关的方法 提供Mapper接口所对应的SQL映射文件 以及 方法对应的SQL语句.
*
* 基于MP: 让XxxMapper接口继承 BaseMapper接口即可.
* BaseMapper<T> : 泛型指定的就是当前Mapper接口所操作的实体类类型
*
*/
public interface EmployeeMapper extends BaseMapper<Employee> {
// Integer insertEmployee(Employee employee );
// <insert useGeneratedKeys="true" keyProperty="id" > SQL...</insert>
}
applicationContext.xml
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务管理器 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于注解的事务管理 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!-- 配置SqlSessionFactoryBean
Mybatis提供的: org.mybatis.spring.SqlSessionFactoryBean
MP提供的:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
-->
<bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 别名处理 -->
<property name="typeAliasesPackage" value="com.atguigu.mp.beans"></property>
<!-- 注入全局MP策略配置 -->
<property name="globalConfig" ref="globalConfiguration"></property>
</bean>
<!-- 定义MybatisPlus的全局策略配置-->
<bean id ="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!-- 在2.3版本以后,dbColumnUnderline 默认值就是true -->
<property name="dbColumnUnderline" value="true"></property>
<!-- 全局的主键策略 -->
<property name="idType" value="0"></property>
<!-- 全局的表前缀策略配置 -->
<property name="tablePrefix" value="tbl_"></property>
</bean>
<!--
配置mybatis 扫描mapper接口的路径
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.atguigu.mp.mapper"></property>
</bean>
</beans>
log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
mybatis-config.xml
<?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>
</configuration>
TestMP.java
package com.atguigu.mp.test;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.atguigu.mp.beans.Employee;
import com.atguigu.mp.mapper.EmployeeMapper;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
//ActiveRecord(活动记录)
//ActiveRecord(活动记录)
//ActiveRecord(活动记录)
public class TestMP {
private ApplicationContext ioc =
new ClassPathXmlApplicationContext("applicationContext.xml");
/**
* AR 分页复杂操作
*/
@Test
public void testARPage() {
Employee employee = new Employee();
Page<Employee> page = employee.selectPage(new Page<>(1, 1),
new EntityWrapper<Employee>().like("last_name", "老"));
List<Employee> emps = page.getRecords();
System.out.println(emps);
}
/**
* AR 删除操作
*
* 注意: 删除不存在的数据 逻辑上也是属于成功的.
*/
@Test
public void testARDelete() {
Employee employee = new Employee();
//boolean result = employee.deleteById(2);
// employee.setId(2);
// boolean result = employee.deleteById();
// System.out.println("result:" +result );
boolean result = employee.delete(new EntityWrapper<Employee>().like("last_name", "小"));
System.out.println(result );
}
/**
* AR 查询操作
*/
@Test
public void testARSelect() {
Employee employee = new Employee();
//Employee result = employee.selectById(14);
// employee.setId(14);
// Employee result = employee.selectById();
// System.out.println(result );
// List<Employee> emps = employee.selectAll();
// System.out.println(emps);
// List<Employee > emps=
// employee.selectList(new EntityWrapper<Employee>().like("last_name", "老师"));
// System.out.println(emps);
Integer result = employee.selectCount(new EntityWrapper<Employee>().eq("gender", 0));
System.out.println("result: " +result );
}
/**ActiveRecord(活动记录)
* AR 修改操作
*/
@Test
public void testARUpdate() {
Employee employee = new Employee();
employee.setId(20);
employee.setLastName("宋老湿");
employee.setEmail("sls@atguigu.com");
employee.setGender(1);
employee.setAge(36);
boolean result = employee.updateById();
System.out.println("result:" +result );
}
/**ActiveRecord(活动记录)
* AR 插入操作
*/
@Test
public void testARInsert() {
Employee employee = new Employee();
employee.setLastName("宋老师");
employee.setEmail("sls@atguigu.com");
employee.setGender(1);
employee.setAge(35);
boolean result = employee.insert();
System.out.println("result:" +result );
}
}
pom.xml
<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.atguigu.mp</groupId>
<artifactId>mp01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- mp依赖
mybatisPlus 会自动的维护Mybatis 以及MyBatis-spring相关的依赖
-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
<!--junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
</dependencies>
</project>
理论:
Active Record(活动记录),是一种领域模型模式,特点是一个模型类对应关系型数据库中的
一个表,而模型类的一个实例对应表中的一行记录。
ActiveRecord 一直广受动态语言( PHP 、 Ruby 等)的喜爱,而 Java 作为准静态语言,
对于 ActiveRecord 往往只能感叹其优雅,所以 MP 也在 AR 道路上进行了一定的探索
5.1 如何使用 AR 模式
1) 仅仅需要让实体类继承 Model 类且实现主键指定方法,即可开启 AR 之旅.
@TableName("tbl_employee")
public class Employee extends Model<Employee>{
// .. fields
// .. getter and setter
@Override
protected Serializable pkVal() {
return this.id;
}
5.2 AR 基本 CRUD
1) 插入操作
public boolean insert()
2) 修改操作
public boolean updateById()
3) 查询操作
public T selectById()
public T selectById(Serializable id)
public List<T> selectAll()
public List<T> selectList(Wrapper wrapper)
public int selectCount(Wrapper wrapper)
4)
删除操作
public boolean deleteById()
public boolean deleteById(Serializable id)
public boolean delete(Wrapper wrapper)
5)
分页复杂操作
public Page<T> selectPage(Page<T> page, Wrapper<T> wrapper)
5.3 AR 小结
1) AR 模式提供了一种更加便捷的方式实现 CRUD 操作,其本质还是调用的 Mybatis 对
应的方法,类似于语法糖
语法糖是指计算机语言中添加的某种语法,这种语法对原本语言的功能并没有影响.
可以更方便开发者使用,可以避免出错的机会,让程序可读性更好.
2) 到此,我们简单领略了 Mybatis-Plus 的魅力与高效率,值得注意的一点是:我们提供
了强大的代码生成器,可以快速生成各类代码,真正的做到了即开即用
三:mp3:MyBatisPlus_代码生成器_MP与MBG的简单对比
applicationContext.xml
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务管理器 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于注解的事务管理 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!-- 配置SqlSessionFactoryBean
Mybatis提供的: org.mybatis.spring.SqlSessionFactoryBean
MP提供的:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
-->
<bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 别名处理 -->
<property name="typeAliasesPackage" value="com.atguigu.mp.beans"></property>
<!-- 注入全局MP策略配置 -->
<property name="globalConfig" ref="globalConfiguration"></property>
</bean>
<!-- 定义MybatisPlus的全局策略配置-->
<bean id ="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!-- 在2.3版本以后,dbColumnUnderline 默认值就是true -->
<property name="dbColumnUnderline" value="true"></property>
<!-- 全局的主键策略 -->
<property name="idType" value="0"></property>
<!-- 全局的表前缀策略配置 -->
<property name="tablePrefix" value="tbl_"></property>
</bean>
<!--
配置mybatis 扫描mapper接口的路径
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.atguigu.mp.mapper"></property>
</bean>
</beans>
log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
mybatis-config.xml
<?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>
</configuration>
TestMP.java
package com.atguigu.mp.test;
import javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class TestMP {
/**
* 代码生成 示例代码
*/
@Test
public void testGenerator() {
//1. 全局配置
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(true) // 是否支持AR模式
.setAuthor("weiyunhui") // 作者
.setOutputDir("D:\\workspace_mp\\mp03\\src\\main\\java") // 生成路径
.setFileOverride(true) // 文件覆盖
.setIdType(IdType.AUTO) // 主键策略
.setServiceName("%sService") // 设置生成的service接口的名字的首字母是否为I
// IEmployeeService
.setBaseResultMap(true)
.setBaseColumnList(true);
//2. 数据源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL) // 设置数据库类型
.setDriverName("com.mysql.jdbc.Driver")
.setUrl("jdbc:mysql://localhost:3306/mp")
.setUsername("root")
.setPassword("1234");
//3. 策略配置
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true) //全局大写命名
.setDbColumnUnderline(true) // 指定表名 字段名是否使用下划线
.setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
.setTablePrefix("tbl_")
.setInclude("tbl_employee"); // 生成的表
//4. 包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("com.atguigu.mp")
.setMapper("mapper")
.setService("service")
.setController("controller")
.setEntity("beans")
.setXml("mapper");
//5. 整合配置
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
//6. 执行
ag.execute();
}
}
pom.xml
<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.atguigu.mp</groupId>
<artifactId>mp01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- mp依赖
mybatisPlus 会自动的维护Mybatis 以及MyBatis-spring相关的依赖
-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
<!--junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Apache velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!-- sfl4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
</dependencies>
</project>
理论:代码生成器
1) MP 提供了大量的自定义设置,生成的代码完全能够满足各类型的需求
2) MP 的代码生成器 和 Mybatis MBG 代码生成器:
MP 的代码生成器都是基于 java 代码来生成。MBG 基于 xml 文件进行代码生成
MyBatis 的代码生成器可生成: 实体类、Mapper 接口、Mapper 映射文件
MP 的代码生成器可生成: 实体类(可以选择是否支持 AR)、Mapper 接口、Mapper 映射
文件、 Service 层、Controller 层.
3) 表及字段命名策略选择
在 MP 中,我们建议数据库表名 和 表字段名采用驼峰命名方式, 如果采用下划
线命名方式 请开启全局下划线开关,如果表名字段名命名方式不一致请注解指定,我
们建议最好保持一致。
这么做的原因是为了避免在对应实体类时产生的性能损耗,这样字段不用做映射就能直
接和实体类对应。当然如果项目里不用考虑这点性能损耗,那么你采用下滑线也是没问
题的,只需要在生成代码时配置 dbColumnUnderline 属性就可以
代码生成器依赖
1) 模板引擎
MP 的代码生成器默认使用的是 Apache 的 Velocity 模板,当然也可以更换为别的模板
技术,例如 freemarker。此处不做过多的介绍。
需要加入 Apache Velocity 的依赖
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
2) 加入 slf4j ,查看日志输出信息
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency
MP 代码生成器示例代码
@Test
public void testGenerator() {
//全局配置
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(true) //是否支持AR模式
.setAuthor("weiyunhui") //作者
.setOutputDir("D:\\workspace_my\\mp03\\src\\main\\java")
//生成路径
.setFileOverride(true)//文件覆盖
.setServiceName("%sService") //设置生成的service接口名
首字母是否为I
.setIdType(IdType.AUTO) //主键策略
;
//数据源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL)
.setUrl("jdbc:mysql://localhost:3306/javaEE_0228")
.setDriverName("com.mysql.jdbc.Driver")
.setUsername("root")
.setPassword("1234");
//策略配置
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true) // 全局大写命名
.setDbColumnUnderline(true) //表名 字段名 是否使用下滑
线命名
.setNaming(NamingStrategy.underline_to_camel) // 数据
库表映射到实体的命名策略
.setInclude("tbl_employee") //生成的表
.setTablePrefix("tbl_"); // 表前缀
//包名策略
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("com.atguigu.mp")
.setController("controller")
.setEntity("beans")
.setService("service");
AutoGenerator ag = new
AutoGenerator().setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
ag.execute();
}
ServiceImpl 说明
EmployeeServiceImpl 继承了 ServiceImpl 类,mybatis-plus 通过这种方
式为我们注入了 EmployeeMapper,这样可以使用 service 层默认为我们提供的很
多方法,也可以调用我们自己在 dao 层编写的操作数据库的方法.
MyBatisPlus_插件扩展_PaginationInterceptor分页插件,MyBatisPlus_自定义全局操作,MyBatisPlus_全局Sql注入器应用_逻辑删除,MyBatisPlus_公共字段自动填充_元数据处理器接口,MyBatisPlus_Oracle数据库的基本操作(包括搭建,实体类创建等等)这几个就不详细整理了。