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的依赖


		
			org.mybatis
			mybatis
			3.4.1
		

		
		
			org.mybatis
			mybatis-spring
			1.3.0
		

整合MP

	
			com.baomidou
			mybatis-plus
			2.3
		

2.SqlSession中的Bean的类型不同

MP中的class


MyBatis中的class


		
		
		
	


构建项目Spring+MyBatis-Plus

项目下载:点击打开链接

MP比MyBatis的优势就是省去了mapper.xml,那么问题来了,没有mapper.xml怎么有SQL和方法呢

这里就是MP给实现的,注意看下面的dao层,就是继承了一个接口BaseMapper

项目结构

MyBatis-Plus整合Spring Demo_第1张图片

pom.mxl


	4.0.0
	com.imooc
	MyBatisPlus
	0.0.1-SNAPSHOT
	
		
			com.baomidou
			mybatis-plus
			2.3
		
		
		
			junit
			junit
			4.11
			test
		
		
		
		
			ch.qos.logback
			logback-classic
			1.1.1
		

		
		
			mysql
			mysql-connector-java
			5.1.39
		

		
		
			com.mchange
			c3p0
			0.9.5.2
		

		
		
			org.springframework
			spring-core
			4.3.10.RELEASE
		
		
			org.springframework
			spring-beans
			4.3.10.RELEASE
		
		
			org.springframework
			spring-web
			4.3.10.RELEASE
		
		
			org.springframework
			spring-jdbc
			4.3.10.RELEASE
		


		

		
	

spring配置文件




	
	

	
	

	
	
		
		
		
		
		
		
	


	
	
		
		
		
		
		
		
		
		
		
		   
		       
		       
		       
		       
		           
		           	     
		       
		   
		
		
	


    
	
		
		
		
		
		

		
		
	

	
		
		
		
	


	
	
		
	



	
	









MyBatis配置文件






	
	
		
	

数据库配置文件

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{

}


测试层

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 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 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 page = new Page<>(2, 2);// currect,size
		List emps = employeeDao.selectPage(page, null);
		System.out.println(emps);
	}

	/**
	 * 按照条件查询
	 */
	@Test
	public void selectByMap() {
		Map columnMap = new HashMap<>();
		columnMap.put("gender", 1);
		columnMap.put("age", 1);
		List 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 idList = new ArrayList<>();
		idList.add(1);
		idList.add(2);
		idList.add(3);
		List 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);
		Listemps=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 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 emps=employeeDao.selectList(wrapper);
		System.out.println(emps);
		
	}
	
	/**同上
	 * R
	 * U
	 * D
	 */
	//@Test
	public void RUD_EntityWrapper(){
		EntityWrapper 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 page=new Page<>(1, 2);
		EntityWrapper wrapper=new EntityWrapper<>();
		//wrapper.between(column, val1, val2) 注意:column是数据库字段,不是类的属性
		wrapper
		//.between("age", 10, 20)//查询age字段在10-20之间的记录
		.eq("gender", 1);//查询字段为gender为1的记录
		
		
		List 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 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);
		
		

	}

}

你可能感兴趣的:(【MyBatis】)