mybatis-plus通用crud

package com.wuluyang.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;
import lombok.Data;

/**
 * @description:实体类
 * @author: 猿始天尊
 * @createDate: 2019/10/17 0017 on 下午 1:39
 * @version: 1.0
 */
@Data
@TableName("tbl_employee")
public class Employee {
    @TableId(type = IdType.AUTO)
    private Integer id ;   //  int
    @TableField("last_name")
    private String  lastName;
    private String  email ;
    private Integer gender;
    private Integer age ;
    @TableField(exist = false)
    private Double salary;


}
======================================mapper接口============================================

package com.wuluyang.mapper;


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

/**
 * @description:mapper接口
 * @author: 猿始天尊
 * @createDate: 2019/10/17 0017 on 下午 1:39
 * @version: 1.0
 */
public interface EmployeeMapper extends BaseMapper<Employee> {


}
================================通用mapper测试类=============================================

package com.wuluyang.test;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;


/**
 * @description:通用mapper测试类
 * @author: 猿始天尊
 * @createDate: 2019/10/17 0017 on 下午 1:38
 * @version: 1.0
 */
public class TestMP {

    private ApplicationContext ioc =
            new ClassPathXmlApplicationContext("application.xml");

    private EmployeeMapper employeeMapper =
            ioc.getBean("employeeMapper",EmployeeMapper.class);

    /**
     * 通用插入操作
     */
    @Test
    public  void insertCommon(){

        Employee employee = new Employee();
        employee.setLastName("yuantian");
      //  employee.setAge(23);
        employee.setEmail("752305564@qq.com");
      //  employee.setGender(1);
        employee.setSalary(12.99);
        //插入到数据库
        int rows = employeeMapper.insert(employee);

        System.out.println("影响行数:"+rows);
        Integer key = employee.getId();
        System.out.println("key:"+key);
    }

    /**
     * 通用 更新操作
     */
    @Test
    public  void CommonUpdate(){
        //初始化修改对象
        Employee employee = new Employee();
        employee.setId(6);
        employee.setLastName("mybatisplus");
        employee.setEmail("mybatisPlus@sina.com");
        employee.setGender(1);
        employee.setAge(35);
        int result = employeeMapper.updateById(employee);

        System.out.println(result);
    }

    /**
     * 通用查询操作
     */
    @Test
    public  void  selectCommon(){
        //1.通过id查询
       /* Employee employee = employeeMapper.selectById(6);
        System.out.println(employee);*/
        //2.通过多个列进行查询
        /*Employee employee = new Employee();
        employee.setId(7);
        employee.setLastName("yangyang");
        Employee result = employeeMapper.selectOne(employee);
        System.out.println(result);*/
        //3.通过多个id进行查询
        /*List<Integer> idList = new ArrayList<Integer>();
        idList.add(6);
        idList.add(7);
        idList.add(8);
        idList.add(9);
        List<Employee> emps = employeeMapper.selectBatchIds(idList);
        System.out.println(emps);*/
        //4.通过map封装条件查询
       /* Map<String,Object> columnMap = new HashMap<String, Object>();
        columnMap.put("last_name","Tom");
        columnMap.put("gender",1);
        List<Employee> emps = employeeMapper.selectByMap(columnMap);
        System.out.println(emps);*/
       //5.分页查询
        List<Employee> emps = employeeMapper.selectPage(new Page<Employee>(2, 2), null);
        System.out.println(emps);

    }
/**
 * 通用删除操作
 */
        @Test
        public void deleteCommon(){
            //1.根据id删除
           /* Integer row = employeeMapper.deleteById(7);
            System.out.println("删除行数:"+row);*/
            //2.根据条件删除
            /*Map<String,Object> columnMap = new HashMap<String, Object>();
            columnMap.put("last_name","yuantian");
            columnMap.put("email","752305564@qq.com");
            Integer rows = employeeMapper.deleteByMap(columnMap);
            System.out.println("删除:"+rows);*/
            //3.批量删除
            List<Integer> idList = new ArrayList<Integer>();
            idList.add(6);
            idList.add(8);
            Integer rows = employeeMapper.deleteBatchIds(idList);
            System.out.println("删除:"+rows);
        }
        //条件构造器
        @Test
        public  void entittyWrapperSelect(){
            //需求1:分页查询 tbl_employee 表中,年龄在 18~50 之间性别为男且姓名为Tom 的所有用户
            //1.条件构造器的selectPage方法
           /* List<Employee> employees = employeeMapper.selectPage(new Page<Employee>(1, 2),
                    new EntityWrapper<Employee>()
                            .between("age", 18, 50)
                            .eq("gender", "1")
                            .eq("last_name", "Tom")

            );
            System.out.println(employees);*/

            //需求2:查询tbl_employee表中,性别为女并且名字中带有"老师"或者邮箱中带有"a"
            List<Employee> employees = employeeMapper.selectList(
                    new EntityWrapper<Employee>()
                            .eq("gender", 0)
                            .like("last_name", "老师")
                           // .or("email", "a")   //SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (gender = ? AND last_name LIKE ? OR email)
                            .orNew("email","a")
            );
            System.out.println(employees);
        }


}
====================application.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="db.properties"/>
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
    </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
        MP提供的: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.wuluyang.entity"></property>


        <!-- 注入全局MP策略配置 -->
        <property name="globalConfig" ref="globalConfiguration"></property>
    </bean>

    <!-- 定义MybatisPlus的全局策略配置-->
    <bean id ="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
        <!-- 在2.3版本以后,dbColumnUnderline 默认值就是true -->
        <property name="dbColumnUnderline" value="true"></property>

        <!-- 全局的主键策略 -->
        <property name="idType" value="0"></property>

        <!-- 全局的表前缀策略配置 -->
        <property name="tablePrefix" value="tbl_"></property>




    </bean>





    <!--
        配置mybatis 扫描mapper接口的路径
     -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wuluyang.mapper"></property>
    </bean>


</beans>

=========================db.properties===================================

# 数据库连接信息
jdbc.user=root
jdbc.password=922115
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf-8&useSSL=false

====================log4j.xml============================

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

==========================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>
    <settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值