码迷,mamicode.com
首页 > 其他好文 > 详细

MybatisPlus 基本增删改查CRUD

时间:2020-02-06 23:19:30      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:system   map   tin   png   incr   编写   过多   getc   扫描   

数据库:

技术图片

 依赖:

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

    }


}

 

MybatisPlus 基本增删改查CRUD

标签:system   map   tin   png   incr   编写   过多   getc   扫描   

原文地址:https://www.cnblogs.com/yscec/p/12271300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!