MybatisPlus 基本增删改查CRUD

Posted 西门夜说

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MybatisPlus 基本增删改查CRUD相关的知识,希望对你有一定的参考价值。

数据库:

 依赖:

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

 相关配置文件:

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>

log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration >
    <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>

db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://xxx.xx.xxx.xxx:3306/mp?useUnicode=true&characterEncoding=UTF8
jdbc.username=root
jdbc.password=123456

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
        mybatisplus提供的: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.ytkj.mybatisplus.entity"></property>

        <!--注入全局mybatisplus策略配置-->
        <property name="globalConfig" ref="globalConfiguration"></property>
    </bean>
    <!--
    配置 mybatis 扫描 mapper 接口的路径
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"
                  value="com.ytkj.mybatisplus.mapper"></property>
    </bean>
    <!--定义mybatisplus的全局策略配置 -->
    <bean id="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
        <!--实体类下划线转驼峰-->
        <property name="dbColumnUnderline" value="true"></property>
        <!--配置全局id自增长策略-->
        <property name="idType" value="0"></property>
        <!--全局的表前缀配置-->
        <property name="tablePrefix" value="tbl_"></property>
    </bean>
</beans>

entity:

package com.ytkj.mybatisplus.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;

/**
 * javaBean
 * 定义javaBean中成员变量时所使用的类型
 */

/**
 * @TableName:
 * value:数据库表名
 *
 */
@TableName(value ="tbl_employee" )
public class Employee {
    /*id INT(11) PRIMARY KEY AUTO_INCREMENT,
    last_name VARCHAR(50),
    email VARCHAR(50),
    gender CHAR(1),
    age INT*/
    /**
     * @TableId:
     *  value:指定表中的主键列的列名,如果实体属性名与列名一致可以省略
     *  type:指定主键策略
     *
     */
    @TableId(value = "id",type = IdType.AUTO)
    @TableField( value = "id",exist = true)
    private Integer id;
    @TableField(value = "last_name",exist = true)
    private String lastName;
    @TableField(value = "email",exist = true)
    private String email;
    @TableField(value = "gender",exist =true)
    private Integer gender;
    @TableField(value ="age",exist = true)
    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 +
                \'}\';
    }
}

Mapper:

package com.ytkj.mybatisplus.mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.ytkj.mybatisplus.entity.Employee;

/**
 * mapper接口
 * :基于mybatis:在Mapper接口中编写CRUD相关方法,提供Mapper接口所对应的SQL映射文件一级方法对应的SQL语句
 * :基于mybatisplus:让xxxMapper接口继承baseMapper<T>即可,T指定的就是当前mapper接口所操作的实体类类型
 */
public interface EmployeeMapper  extends BaseMapper<Employee> {

}

Test:

基本增删改查

package junit.test;

import com.baomidou.mybatisplus.plugins.Page;
import com.ytkj.mybatisplus.entity.Employee;
import com.ytkj.mybatisplus.mapper.EmployeeMapper;
import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestMybatisPlus {
    private ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
    @Test
    public void testDataSource() throws SQLException {
        DataSource dataSource=ioc.getBean("dataSource",DataSource.class);
        System.out.println(dataSource);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }


    /**
     * 从容器中获取employeeMapper
     */
    private EmployeeMapper employeeMapper=ioc.getBean("employeeMapper",EmployeeMapper.class);

    /**
     * 通用插入操作  插入实体类设置值的字段,只有非空的属性对应的字段才会出现到SQL语句中
     * INSERT INTO tbl_employee ( last_name, age ) VALUES ( ?, ? )
     */

    @Test
    public void testInsert(){
        Employee employee=new Employee();
        employee.setLastName("zhechaochao");
        employee.setAge(18);
        Integer row = employeeMapper.insert(employee);
        System.out.println("row="+row);

        //获取数据库中的主键值
        Integer id = employee.getId();
        System.out.println(id);
    }

    /**
     * 通用插入操作  插入时不管属性是否非空,属性所对应的字段都会出现到SQL语句中
     * INSERT INTO tbl_employee ( last_name,email,gender,age ) VALUES ( ?,?,?,? )
     */
    @Test
    public void testInsertAllColumn(){
        Employee employee=new Employee();
        employee.setLastName("zhechaochao");
        employee.setAge(18);
        Integer row = employeeMapper.insertAllColumn(employee);
        System.out.println("row="+row);

        //获取数据库中的主键值
        Integer id = employee.getId();
        System.out.println(id);
    }


    /**
     * 根据id更新
     * UPDATE tbl_employee SET gender=?, age=? WHERE id=?
     */
    @Test
    public void testUpdateById(){
        Employee employee=new Employee();
        employee.setId(7);
        employee.setGender(1);
        employee.setAge(25);
        Integer row = employeeMapper.updateById(employee);
        System.out.println("row="+row);
    }

    /**
     * 根据id更新
     * 慎用,更新所有字段 其他字段原本有值会被设置为null
     * UPDATE tbl_employee SET last_name=?,email=?,gender=?,age=? WHERE id=?
     */
    @Test
    public void testUpdateAllColumnById(){
        Employee employee=new Employee();
        employee.setId(7);
        employee.setGender(1);
        employee.setAge(25);
        Integer row = employeeMapper.updateAllColumnById(employee);
        System.out.println("row="+row);
    }


    /**
     * 更具id查询
     * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id=?
     */
    @Test
    public void testSelectById(){
        Employee employee = employeeMapper.selectById(1);
        System.out.println(employee);
    }

    /**
     *通过多列进行查询 id+lastName
     * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id=? AND last_name=?
     */
    @Test
    public void testSelectOne(){
        Employee employee=new Employee();
        employee.setId(6);
        employee.setLastName("zhechaochao");
        Employee employee1 = employeeMapper.selectOne(employee);
        System.out.println(employee1);
    }

    /**
     *根据id批量查询
     * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id IN ( ? , ? , ? )
     */
    @Test
    public void testSelectBatchIds(){
        List<Integer> list=new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(6);
        List<Employee> employees = employeeMapper.selectBatchIds(list);
        System.out.println(employees);
    }

    /**
     *通过map封装查询条件
     * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE gender = ? AND last_name = ? AND id = ?
     */
    @Test
    public void testSelectByMap(){
        Employee employee=new Employee();
        Map<String,Object> map=new HashMap<>();
        /**
         * put时是数据库中的列名而不是实体类的属性名
         */
        map.put("id",1);
        //map.put("lastName","Tom");报错
        map.put("last_name","Tom");
        map.put("gender",1);
        List<Employee> employees = employeeMapper.selectByMap(map);
        System.out.println(employees);
    }

    /**
     *不根据条件分页查询
     * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee
     */
    @Test
    public void testSelectPage(){
        RowBounds rowBounds=new RowBounds(0,2);
        List<Employee> employees = employeeMapper.selectPage(rowBounds, null);
        System.out.println("employees"+employees);


        Page<Employee> page=new Page<>(0,2);
        List<Employee> employees1 = employeeMapper.selectPage(page, null);
        System.out.println("employees1"+employees1);

    }


    /**
     *根据id删除
     * DELETE FROM tbl_employee WHERE id=?
     */
    @Test
    public void testDeleteById(){
        Integer row = employeeMapper.deleteById(7);
        System.out.println("row"+row);

    }
    /**
     *根据id批量删除
     * DELETE FROM tbl_employee WHERE id IN ( ? , ? )
     */
    @Test
    public void testDeleteBatchIds(){
        List<Integer> list=new ArrayList<>();
        list.add(8);
        list.add(9);
        Integer row = employeeMapper.deleteBatchIds(list);
        System.out.println("row"+row);

    }

    /**
     *通过map封装删除条件
     * DELETE FROM tbl_employee WHERE last_name = ? AND id = ? AND age = ?
     */
    @Test
    public void testDeleteByMap(){
        Map<String,Object> map=new HashMap<>();
        map.put("id",6);
        map.put("last_name","zhechaochao");
        map.put("age",18);
        Integer row = employeeMapper.deleteByMap(map);
        System.out.println("row"+row);

    }


}

 条件构造器删改查

package junit.test;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ytkj.mybatisplus.entity.Employee;
import com.ytkj.mybatisplus.mapper.EmployeeMapper;
import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestMybatisPlusConditionalQuery {
    private ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
    @Test
    public void testDataSource() throws SQLException {
        DataSource dataSource=ioc.getBean("dataSource",DataSource.class);
        System.out.println(dataSource);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }


    /**
     * 从容器中获取employeeMapper
     */
    private EmployeeMapper employeeMapper=ioc.getBean("employeeMapper",EmployeeMapper.class);

    /**
     * 条件构造器 查询操作
     * 年龄在 18~50 之间性别为男且姓名为 xx 的所有用户
     *SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (age BETWEEN ? AND ? AND gender = ? AND last_name = ?)
     */

    @Test
    public void testSelectPage(){
        Page<Employee> page=new Page<>(0,2);
        EntityWrapper<Employee> entityWrapper=new EntityWrapper<>();
        entityWrapper.between("age",18,50).eq("gender",1).eq("last_name","Tom");
        List<Employee> list = employeeMapper.selectPage(page, entityWrapper);
        System.out.println(list);
    }

    /**
     * 条件构造器 查询操作
     * 性别为女并且名字中带有laoshi或者邮箱中带有a
     *or()===>SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (gender = ? AND last_name LIKE ? OR email LIKE ?)
     * orNew()===>SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (gender = ? AND last_name LIKE ?) OR (email LIKE ?)
     *
     */

    @Test
    public void testSelectList(){
        EntityWrapper<Employee> entityWrapper=new EntityWrapper<>();
        //entityWrapper.eq("gender",0).like("last_name","laoshi").or().like("email","a");
        entityWrapper.eq("gender",0).like("last_name","laoshi").orNew().like("email","a");
        List<Employee> employees = employeeMapper.selectList(entityWrapper);
        System.out.println(employees);
    }

    /**
     * 条件构造器 查询操作
     * 名字为Tom性别为男根据年龄排序
     * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (gender = ? AND last_name = ?) ORDER BY age DESC
     *
     */

    @Test
    public void testSelectList2(){
        EntityWrapper<Employee> entityWrapper=new EntityWrapper<>();
        entityWrapper.eq("gender",1).eq("last_name","Tom").orderBy("age",false);
        List<Employee> employees = employeeMapper.selectList(entityWrapper);
        System.out.println(employees);
    }

    /**
     * 条件构造器 查询操作
     * 根据名字长度大于10分组
     * 更具性别分组,查询每组的平均年龄,最大年龄,最小年龄。并且只取平均年龄大于21的组
     * SELECT MAX(age),MIN(age),AVG(age) FROM tbl_employee GROUP BY gender HAVING (avg(age)>21)
     */

    @Test
    public void testSelectMaps(){
        EntityWrapper<Employee> entityWrapper=new EntityWrapper<>();
        entityWrapper.setSqlSelect("MAX(age),MIN(age),AVG(age)").groupBy("gender").having("avg(age)>21");
        List<Map<String, Object>> list = employeeMapper.selectMaps(entityWrapper);
       list.forEach(System.out::println);
    }



    /**
     * 条件构造器 修改操作
     *名字为xiaohong并且性别为女年龄为10的人名字改为honghonglaoshi,邮箱改为120@qq.com
     * UPDATE tbl_employee SET last_name=?, email=? WHERE (last_name = ? AND gender = ? AND age = ?)
     */
    @Test
    public void testUpdate(){
        Employee employee=new Employee();
        employee.

以上是关于MybatisPlus 基本增删改查CRUD的主要内容,如果未能解决你的问题,请参考以下文章

mybatis怎么进行增删改查

掌握MyBatisPlus中的分页及条件查询构建 | 黑马程序员

goweb之书城基本CRUD增删改查

基于SSM之Mybatis接口实现增删改查(CRUD)功能

MySQL代码建表增删改查(CRUD)

无需编程,基于PostgreSQL零代码生成CRUD增删改查RESTful API接口