1.mybatis-plus之通用 CRUD 封装BaseMapper

本文章主要演示如何使用mybatis-plus的接口BaseMapper实现CURD相关操作,演示环境为Idea+maven+spring+mybatis,并使用单元测试的形式展示。

1.maven环境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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>MP1artifactId>
    <version>1.0-SNAPSHOTversion>
    <dependencies>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plusartifactId>
            <version>2.3version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.9version>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.2version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.37version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>4.3.10.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>4.3.10.RELEASEversion>
        dependency>

    dependencies>
project>

2. POJO类:Emp.java

package com.qwy.bean;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.enums.IdType;

import java.util.Date;

/**
 * @author qwy
 * @create 2021-04-09 8:41
 **/
public class Emp {
    /*设置主键名称默认为id*/
    @TableId(value = "empno",type = IdType.INPUT)
    private Integer empno;
    private String ename;
    private String job;
    private Integer mgr;
    private Date hiredate;
    private Float sal;
    private Float comm;
    private Integer deptno;

    public Emp() {
    }

    public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Float sal, Float comm, Integer deptno) {
        this.empno = empno;
        this.ename = ename;
        this.job = job;
        this.mgr = mgr;
        this.hiredate = hiredate;
        this.sal = sal;
        this.comm = comm;
        this.deptno = deptno;
    }

    public Integer getEmpno() {
        return empno;
    }

    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Integer getMgr() {
        return mgr;
    }

    public void setMgr(Integer mgr) {
        this.mgr = mgr;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public Float getSal() {
        return sal;
    }

    public void setSal(Float sal) {
        this.sal = sal;
    }

    public Float getComm() {
        return comm;
    }

    public void setComm(Float comm) {
        this.comm = comm;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "empno=" + empno +
                ", ename='" + ename + '\'' +
                ", job='" + job + '\'' +
                ", mgr=" + mgr +
                ", hiredate=" + hiredate +
                ", sal=" + sal +
                ", comm=" + comm +
                ", deptno=" + deptno +
                '}';
    }
}

3. 持久层接口:EmpMapper.java

注意:继承BaseMapper接口

package com.qwy.mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.qwy.bean.Emp;

/**
 * @author qwy
 * @create 2021-04-14 23:35
 **/
public interface EmpMapper extends BaseMapper<Emp> {
}

4.数据库资源文件:db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=root
jdbc.password=admin

5. 日志文件:log4j.xml



 
<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>

6.mybatis的核心配置文件:mybatis-config.xml



<configuration>
	
configuration>

7.spring的全局配置文件:applicationContext.xml


<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="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource">property>
	bean>
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	
	

	<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>		
		
		
		<property name="globalConfig" ref="globalConfiguration">property>
	bean>
	
	
	
		
		<property name="dbColumnUnderline" value="true">property>
		
		
		<property name="idType" value="0">property>
		
		
		
	
	bean>
	
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.qwy.mapper">property>
	bean>
	
	
beans>

8.通用CURD测试类

package com.qwy.test;

import com.qwy.bean.Emp;
import com.qwy.mapper.EmpMapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author qwy
 * @create 2021-04-14 23:36
 **/
public class TestCommonCURD {

    private EmpMapper empMapper=null;
    @Before
    public void getApplicationContext(){
         ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");
         empMapper=ac.getBean("empMapper",EmpMapper.class);
    }

    /**
     * 添加:
     * insert()方法,会将设置为null属性对应字段忽略
     */
    @Test
    public void testInsert(){
        Emp emp= new Emp(1111, "admin", "CLERK", 7788, null, 2000F,null, 10);
        //SQL:INSERT INTO emp ( empno, ename, job, mgr, sal, deptno ) VALUES ( ?, ?, ?, ?, ?, ? )
        Integer insert = empMapper.insert(emp);
        System.out.println("insert = " + insert);
    }

    /**
     * 添加
     * insertAllColumn(),会将属性为null的字段也在SQL操作
     *
     */
    @Test
    public void testInsertAllColumn(){
        Emp emp= new Emp(3333, "admin", "CLERK", 7788, null, 2000F,null, 10);
        //SQL:INSERT INTO emp ( empno,ename,job,mgr,hiredate,sal,comm,deptno ) VALUES ( ?,?,?,?,?,?,?,? )
        Integer insert = empMapper.insertAllColumn(emp);
        System.out.println("insert = " + insert);
    }

    /**
     * 根据id更新操作:
     * updateById();根据id更新,忽略为null的字段
     */
    @Test
    public void testUpdateById(){
        Emp emp= new Emp(1111, "齐老师", "CLERK", 7788, null, 2000F,null, 10);
        //SQL:UPDATE emp SET ename=?, job=?, mgr=?, sal=?, deptno=? WHERE empno=?
        Integer integer = empMapper.updateById(emp);
        System.out.println("integer = " + integer);
    }

    /**
     * 根据id更新操作:
     * 会将属性为null的字段也在SQL操作
     */
    @Test
    public void testUpdateAllColumnById(){
        Emp emp= new Emp(1111, "齐大大", "CLERK", 7788, null, 2000F,null, 10);
        //SQL:UPDATE emp SET ename=?,job=?,mgr=?,hiredate=?,sal=?,comm=?,deptno=? WHERE empno=?
        Integer integer = empMapper.updateAllColumnById(emp);
        System.out.println("integer = " + integer);
    }

    /**
     * 根据id删除
     */
    @Test
    public void testDeleteById(){
        //SQL:DELETE FROM emp WHERE empno=?
        Integer integer = empMapper.deleteById(1111);
        System.out.println("integer = " + integer);
    }

    /**
     * 根据id批量删除
     */
    @Test
    public void testDeleteBatchIds(){
        //SQL:DELETE FROM emp WHERE empno IN ( ? , ? , ? )
        Integer integer = empMapper.deleteBatchIds(Arrays.asList(2222,3333,4444));
        System.out.println("integer = " + integer);
    }

    /**
     * 根据条件删除:
     * map的key为字段,value为字段的值
     */
    @Test
    public void testDeleteByMap(){
        Map<String,Object> conditons= new HashMap<String, Object>();
        conditons.put("empno",1111);
        conditons.put("ename","admin");
        //SQL: DELETE FROM emp WHERE ename = ? AND empno = ?
        Integer integer = empMapper.deleteByMap(conditons);
        System.out.println("integer = " + integer);
    }


}

9.get获取测试类

package com.qwy.test;

import com.baomidou.mybatisplus.plugins.Page;
import com.qwy.bean.Emp;
import com.qwy.mapper.EmpMapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author qwy
 * @create 2021-04-14 23:36
 **/
public class TestGet {

    private EmpMapper empMapper=null;
    @Before
    public void getApplicationContext(){
         ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");
         empMapper=ac.getBean("empMapper",EmpMapper.class);
    }

    /**
     * 根据主键查询
     */
    @Test
    public void testSelectById(){
        //SQL:SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE empno=?
        Emp emp = empMapper.selectById(7788);
        System.out.println("emp = " + emp);
    }

    /**
     * 根据条件查询单个实体,如果返回多条数据,报错
     */
    @Test
    public void testSelectOne(){
        Emp conditions= new Emp();
        conditions.setEmpno(7788);
        conditions.setEname("SCOTT");
        //SQL:SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE empno=? AND ename=?
        Emp emp = empMapper.selectOne(conditions);
        System.out.println("emp = " + emp);
    }

    /**
     * 根据id批量查询
     */
    @Test
    public void testSelectBatchIds(){

        //SQL:SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE empno IN ( ? , ? , ? )
        List<Emp> emps = empMapper.selectBatchIds(Arrays.asList(7788, 1111, 7369));
        System.out.println("emps = " + emps);
    }

    /**
     * 使用map集合作为条件
     */
    @Test
    public void testSelectByMap(){
        Map<String ,Object> conditions=new HashMap<String, Object>();
        conditions.put("deptno",30);
        //SQL:SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE deptno = ?
        List<Emp> emps = empMapper.selectByMap(conditions);
        for (int i = 0; i < emps.size(); i++) {
            System.out.println("emps = " + emps.get(i));
        }
    }

    /**
     * 分页:基于内存的分页
     *
     */
    @Test
    public void testSelectPage(){

        //SQL:SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp
        List<Emp> emps = empMapper.selectPage(new Page<Emp>(1,3),null);
        for (int i = 0; i < emps.size(); i++) {
            System.out.println("emps = " + emps.get(i));
        }
    }




}

10. 条件构造测试类

package com.qwy.test;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qwy.bean.Emp;
import com.qwy.mapper.EmpMapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author qwy
 * @create 2021-04-14 23:36
 **/
public class TestEntityWrapper {

    private EmpMapper empMapper=null;
    @Before
    public void getApplicationContext(){
         ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");
         empMapper=ac.getBean("empMapper",EmpMapper.class);
    }

    /**
     * 根据主键查询
     */
    @Test
    public void testSelectCount(){
        EntityWrapper<Emp> wrapper = new EntityWrapper<Emp>();
        wrapper.eq("deptno",30);
        wrapper.like("ename","A");
        Integer count = empMapper.selectCount(wrapper);
        System.out.println("count = " + count);
    }

    /**
     * 根据条件查询返回list集合封装的Map集合结果:
     * map的key为字段名,value为对应字段的值
     */
    @Test
    public void testSelectMaps(){
        EntityWrapper<Emp> wrapper = new EntityWrapper<Emp>();
        wrapper.eq("deptno",30);
        wrapper.like("ename","A");
        //SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE (deptno = ? AND ename LIKE ?)
        List<Map<String, Object>> list = empMapper.selectMaps(wrapper);
        System.out.println("list = " + list);
    }

    /**
     * 条件查询,返回list集合封装的对象
     *
     */
    @Test
    public void testSelectList(){
        EntityWrapper<Emp> wrapper = new EntityWrapper<Emp>();
        wrapper.eq("deptno",30);
        wrapper.like("ename","A");
        //SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE (deptno = ? AND ename LIKE ?)
        List<Emp> emps = empMapper.selectList(wrapper);
        System.out.println("emps = " + emps);
    }

    /**
     * 基于内存的分页查询方式
     * 返回list集合封装的对象
     */
    @Test
    public void testSelectPage(){
        EntityWrapper<Emp> wrapper = new EntityWrapper<Emp>();
        wrapper.eq("deptno",30);
        wrapper.like("ename","A");
        //SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE (deptno = ? AND ename LIKE ?)
        List<Emp> emps = empMapper.selectPage(new Page<Emp>(2,3),wrapper);
        System.out.println("emps = " + emps);
    }
    /**
     * 基于内存的分页查询方式
     * 返回list集合封装的map集合
     */
    @Test
    public void testSelectMapsPage(){
        EntityWrapper<Emp> wrapper = new EntityWrapper<Emp>();
        wrapper.eq("deptno",30);
        wrapper.like("ename","A");
        //SELECT empno AS empno,ename,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE (deptno = ? AND ename LIKE ?)
        List<Map<String, Object>> maps = empMapper.selectMapsPage(new Page<Emp>(2, 3), wrapper);
        System.out.println("maps = " + maps);
    }

    /**
     * 根据条件修改
     */
    @Test
    public void testUpdate(){
        EntityWrapper<Emp> wrapper = new EntityWrapper<Emp>();
        wrapper.eq("deptno",10);
        wrapper.eq ("empno","1111");
        Emp emp= new Emp(1111, "aaaa", "CLERK", 7788, null, 2000F,null, 10);
        // UPDATE emp SET ename=?, job=?, mgr=?, sal=?, deptno=? WHERE (deptno = ? AND empno = ?)
        Integer update = empMapper.update(emp, wrapper);
        System.out.println("update = " + update);
    }

    /**
     * 根据条件删除
     */
    @Test
    public void testDelete(){
        EntityWrapper<Emp> wrapper = new EntityWrapper<Emp>();
        wrapper.eq("deptno",10);
        wrapper.eq ("empno","1111");

        // DELETE FROM emp WHERE (deptno = ? AND empno = ?)
        Integer delete = empMapper.delete(wrapper);

        System.out.println("delete = " + delete);
    }

    /**
     * 根据条件删除
     */
    @Test
    public void testDelete2(){

        Condition condition = Condition.create();
        condition.eq("deptno",10);
        condition.eq ("empno","1111");
        // DELETE FROM emp WHERE (deptno = ? AND empno = ?)
        Integer delete = empMapper.delete(condition);

        System.out.println("delete = " + delete);
    }
}

11.常用CURD方法整理

11.1Insert
// 插入一条记录
int insert(T entity);
11.2.Delete
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
11.3.Update
// 根据 whereEntity 条件,更新记录
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);
11.4.Select
// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);

// 查询(根据ID 批量查询)
List selectBatchIds(@Param(Constants.COLLECTION) Collection idList);
// 根据 entity 条件,查询全部记录
List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);
// 查询(根据 columnMap 条件)
List selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
// 根据 Wrapper 条件,查询全部记录
List> selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List selectObjs(@Param(Constants.WRAPPER) Wrapper queryWrapper);

// 根据 entity 条件,查询全部记录(并翻页)
IPage selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage> selectMapsPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);
 
  

转载请加入出处

你可能感兴趣的:(mybatis,mybatis-plus,mybatis,mysql,spring,数据库,单元测试)