MyBatis-Plus整合Spring Demo

简介

官方文档:苞米豆

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("8@com10");
		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("8@com10");
		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("8@com");
		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);
		
		

	}

}

猜你喜欢

转载自blog.csdn.net/qq_37171353/article/details/80887280