mybatis_plus

1.1 What is Mybatis-Plus

Plus-MyBatis (abbreviated MP) is a  MyBatis  enhancement tools, based on MyBatis only enhance not changed , to simplify development, increase efficiency and health.

 

1.2 Why learn Mybatis-Plus

We have learned Mybatis this framework, we only need to define the abstract interface dao layer, based on the characteristics Mybatis zero achieve, you can achieve crud operation of the database.

 

The following two interfaces:

 

UserMapper Interface

public interface UserMapper {

 

    int deleteByPrimaryKey(Long id);

    int insert(User user);

    List<User> selectList();

    User selectByPrimaryKey(Long id);

}

 

OrderMapper Interface

public interface OrderMapper {

 

    int deleteByPrimaryKey(Long id);

    int insert(Order order);

    List<Order> selectList();

    User selectByPrimaryKey(Long id);

}

 

In the above two business interface, we found that: they define a set of similar crud method.

 

In more type of business, when this group of functionally similar interface methods we need to repeat the definition.

 

How to solve this problem?

 

Use Mybatis-plus tools, we only need to define the abstract interface we inherit a common BaseMapper <T> interface, you can get a common set of crud way to operate the database! ! !

 

When using Mybatis-plus, you do not even need any xml mapping files or annotations interface method, the real realization dao layer zero.

 

1.3 Mybatis-Plus Summary

Mybatis-Plus only on the basis of Mybatis on the realization of the enhancements, allowing developers to more simple and efficient.

 

Mybatis-Plus does not modify any of the characteristics Mybatis! ! !

 

2 start example

2.1 Requirements

Use Mybatis-Plus achieve crud operations for the user.

 

2.2 Configuration step described

(1) build environment (creating a project, import the package)

(2) Configuration Mybaits-Plus (Spring-based implementation)

(3) writing test code

 

2.3 Configuration Step

2.3.1 The first step: build environment

2.3.1.1 premise

We have created a database environment:

 

 

Construction of the table statement:

CREATE TABLE `tb_user` (

  `id` bigint(20) NOT NULL COMMENT '主键ID',

  `name` varchar(30) DEFAULT NULL COMMENT '姓名',

  `Age` int (11) DEFAULT NULL COMMENT 'Age'

  `Email` varchar (50) DEFAULT NULL COMMENT 'mailbox',

  PRIMARY KEY (`id`)

)

 

2.3.1.2 Description

(1) Mybatis-Plus does not provide a separate jar package, but through Maven (or Gradle) to manage dependency jar. This tutorial requires the use Maven to build the project.

 

(2) Mybatis-Plus is based on the Spring Framework implementation, the use Mybatis-Plus, you must import the relevant dependent Spring.

 

2.3.1.3 Creating project

 

 

2.3.1.4 add dependencies

修改pom.xml文件,添加Mybatis-Plus相关依赖:

<dependencies>

       <dependency>

           <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus</artifactId>

            <version>2.3</version>

       </dependency>

      

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-context</artifactId>

           <version>4.3.16.RELEASE</version>

       </dependency>

      

       <!-- MySql -->

        <dependency>

           <groupId>mysql</groupId>

           <artifactId>mysql-connector-java</artifactId>

           <version>5.1.40</version>

       </dependency>

 

       <!-- 连接池 -->

       <dependency>

           <groupId>com.alibaba</groupId>

           <artifactId>druid</artifactId>

           <version>1.0.9</version>

       </dependency>

          

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-jdbc</artifactId>

           <version>4.3.16.RELEASE</version>

       </dependency>

          

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-test</artifactId>

           <version>4.3.16.RELEASE</version>

           <scope>test</scope>

       </dependency>

          

       <dependency>

           <groupId>junit</groupId>

           <artifactId>junit</artifactId>

           <version>4.12</version>

           <scope>test</scope>

       </dependency>

       <!-- 导入切面依赖包 -->

       <dependency>

           <groupId>org.springframework</groupId>

           <artifactId>spring-aspects</artifactId>

           <version>4.3.16.RELEASE</version>

       </dependency>

  </dependencies>

 

2.3.2        第二步:创建User实体类

说明:使用Mybatis-Plus可以不使用xml文件,而是基于一组注解来解决实体类数据库表映射问题。

 

@TableName(value="tb_user")

指定对应的表,表名和类名一致时,可以省略value属性。

@TableId

指定表的主键。Value属性指定表的主键字段,和属性名一致时,可以省略。Type指定主键的增长策略。

@TableField

指定类的属性映射的表字段,名称一致时可以省略该注解。

 

User类如下:

package cn.gzsxt.mp.pojo;

 

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("tb_user")

public class User {

   

    @TableId(value = "id", type = IdType.AUTO)

    private Long id; //bigint(20) NOT NULL COMMENT '主键ID',

    @TableField(value = "name")

    private String name; //varchar(30) DEFAULT NULL COMMENT '姓名',

    private String age; //int(11) DEFAULT NULL COMMENT '年龄',

    private String email; //varchar(50) DEFAULT NULL COMMENT '邮箱',

   

//补全get、set方法

 

}

2.3.3        第三步:创建UserMapper接口

说明:继承BaseMapper公共接口即可。

package cn.gzsxt.mp.mapper;

 

import com.baomidou.mybatisplus.mapper.BaseMapper;

 

import cn.gzsxt.mp.pojo.User;

 

public interface UserMapper extends BaseMapper<User>{

 

}

 

2.3.4        第四步:Mybatis-Plus整合Spring

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

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd

       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

 

    <context:component-scan base-package="cn.gzsxt.mp"/>

 

    <!-- 1、创建数据源 -->

    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

       <property name="url" value="jdbc:mysql://localhost:3306/mp"/>

       <property name="username" value="root"/>

       <property name="password" value="gzsxt"/>

      

       <property name="maxActive" value="20"/>

       <property name="minIdle" value="5"/>

    </bean>

   

    <!-- 2、mybatis-plus整合Spring

       任何的数据库的框架,要使用spring的事物代理,必须使用spring提供的数据源,必须整合spring才可以使用

    -->

    <bean name="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">

       <!-- 加载数据源 -->

       <property name="dataSource" ref="dataSource"/>

      

       <!-- 指定pojo目录 -->

       <property name="typeAliasesPackage" value="cn.gzsxt.mp.pojo"/>

      

       <!-- 配置mybatis-plus插件 -->

       <property name="plugins">

           <list>

               <!-- 配置分页插件 -->

              <bean class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"/>

             

              <!-- 配置拦截器属性 -->

              <bean class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">

                  <!-- 配置sql响应时间,开发阶段方便做调优 -->

                  <property name="maxTime" value="1000"/>

                 

                  <property name="format" value="true"/>

                 

              </bean>

           </list>

       </property>

      

       <property name="globalConfig" ref="globalConfiguration"></property>

      

    </bean>

 

    <!-- 3、配置mybatis的动态代理 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

   

       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>

      

       <property name="basePackage" value="cn.gzsxt.mp.mapper"></property>

      

    </bean>

 

    <!-- 4、配置事物管理器 -->

     <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

           <property name="dataSource" ref="dataSource"></property>

     </bean>

   

    <!-- 配置mybatis-plus全局属性 -->

    <!-- 定义 MybatisPlus 的全局策略配置-->

    <bean id ="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">

        <!-- 在 2.3 版本以后,dbColumnUnderline 默认值是 true,即pojo属性开启驼峰标识 -->

        <property name="dbColumnUnderline" value="true"></property>

        <!-- 全局的主键策略 -->

        <!--

            AUTO->`0`("数据库ID自增")

             INPUT->`1`(用户输入ID")

            ID_WORKER->`2`("全局唯一ID")

            UUID->`3`("全局唯一ID")

        -->

        <property name="idType" value="0"></property>

        <!-- 全局的表前缀策略配置 -->

        <property name="tablePrefix" value="tb_"></property>

    </bean>

 

   

    <!-- 5、开启注解声明式事物 -->

    <tx:annotation-driven/>

</beans>

 

 

2.3.5        第五步:编写测试代码

package cn.gzsxt.mp.test;

 

import java.util.List;

 

import org.apache.ibatis.session.RowBounds;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 

import com.baomidou.mybatisplus.mapper.EntityWrapper;

 

import cn.gzsxt.mp.mapper.UserMapper;

import cn.gzsxt.mp.pojo.User;

 

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:spring-data.xml"})

@ComponentScan(basePackages={"cn.gzsxt.mp"})

public class UserMapperTEST {

 

    @Autowired

    private UserMapper userMapper;

   

    //插入一条记录

    @Test

    public void insert(){

       User user = new User();

       user.setAge(18);

       user.setEmail("[email protected]");

       user.setName("张三");

      

       userMapper.insert(user);

    }

   

    //根据id查询

    @Test

    public void selectById(){

       User user = userMapper.selectById(1);

      

       System.out.println("用户id:"+user.getId()+",用户姓名:"+user.getName()+",用户邮箱:"+user.getEmail());

    }

   

    //根据用户名查找

    @Test

    public void selectByName(){

      

       EntityWrapper<User> wrapper = new EntityWrapper<>();

       wrapper.eq("name", "张三");

      

       List<User> users = userMapper.selectList(wrapper);

      

       for (User user : users) {

           System.out.println("用户id:"+user.getId()+",用户姓名:"+user.getName()+",用户邮箱:"+user.getEmail());

       }

    }

   

    //查询用户列表

    @Test

    public void selectAll(){

       List<User> users = userMapper.selectList(null);

       for (User user : users) {

           System.out.println("用户id:"+user.getId()+",用户姓名:"+user.getName()+",用户邮箱:"+user.getEmail());

       }

    }

   

    //分页查询,第2页,每页3条

    @Test

    public void selectAndPage(){

      

       RowBounds rowBounds = new RowBounds((2-1)*3, 3);

      

       List<User> users = userMapper.selectPage(rowBounds, null);

      

       for (User user : users) {

           System.out.println("用户id:"+user.getId()+",用户姓名:"+user.getName()+",用户邮箱:"+user.getEmail());

       }

    }

   

    //模糊查询

    @Test

    public void selectByLike(){

      

       EntityWrapper<User> wrapper = new EntityWrapper<>();

       wrapper.like("name", "%张%");

      

       List<User> users = userMapper.selectList(wrapper);

       for (User user : users) {

          

           System.out.println("用户id:"+user.getId()+",用户姓名:"+user.getName()+",用户邮箱:"+user.getEmail());

       }

    }

}

Guess you like

Origin www.cnblogs.com/w410782823/p/11228216.html