Mybatis-plus快速入門


簡介

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

特性

  • 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
  • 損耗小:啟動即會自動注入基本 CURD,性能基本無損耗,直接面向對象操作
  • 強大的 CRUD 操作:內置通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求
  • 支持 Lambda 形式調用:通過 Lambda 表達式,方便的編寫各類查詢條件,無需再擔心字段寫錯
  • 支持多種數據庫:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多種數據庫
  • 支持主鍵自動生成:支持多達 4 種主鍵策略(內含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解決主鍵問題
  • 支持 XML 熱加載:Mapper 對應的 XML 支持熱加載,對於簡單的 CRUD 操作,甚至可以無 XML 啟動
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式調用,實體類只需繼承 Model 類即可進行強大的 CRUD 操作
  • 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 支持關鍵詞自動轉義:支持數據庫關鍵詞(order、key......)自動轉義,還可自定義關鍵詞
  • 內置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來使用
  • 內置分頁插件:基於 MyBatis 物理分頁,開發者無需關心具體操作,配置好插件之后,寫分頁等同於普通 List 查詢
  • 內置性能分析插件:可輸出 Sql 語句以及其執行時間,建議開發測試時啟用該功能,能快速揪出慢查詢
  • 內置全局攔截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規則,預防誤操作
  • 內置 Sql 注入剝離器:支持 Sql 注入剝離,有效預防 Sql 注入攻擊

 

這個Mybatis增強版是咱國人開發的,也是值得驕傲的地方,他跟JPA感覺還是Plus舒服點,整合SpringBoot更加加大開發效率

一、快速上手

  1.前置知識

Mybatis,Spring,Maven

  2.創建表

2.添加Maven依賴

 <!-- mp依賴
             mybatisPlus 會自動的維護Mybatis 以及MyBatis-spring相關的依賴
         -->
        <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>

  3.項目架構圖

4.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
		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.mp.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.mp.mapper"></property>
	</bean>
	
	
</beans>

  5.log4j.xml

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

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="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.db.properties(Mybatis-Config.xml可省略)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mp
jdbc.username=root
jdbc.password=146903

  7.JavaBeans

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

//次注解標注表名
@TableName(value = "mp")
public class Mp {
    //value:如果ID對應數據庫可省略 type:指定主鍵策略
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

     //跟數據庫列名對應
     @TableField("last_name")
    private String lastName;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    private String email;

    private Integer gender;

    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 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 "Mp{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", age=" + age +
                '}';
    }
}

  8.MpMapper(接口)

package com.mp.mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.mp.entity.Mp;

import org.springframework.stereotype.Component;

/*
* :泛型指定當前接口Mapper接口所操作的實體類
* */
@Component("MpMapper")
public interface MpMapper  extends BaseMapper<Mp> {

}

  你沒有看錯Mapper接口什么都不用寫,只需繼承BaseMapper<T>

9.最后一步 測試類

package com.mp.test;


import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mp.entity.Mp;
import com.mp.mapper.MpMapper;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

public class Test {

    private ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    MpMapper mpMapper = applicationContext.getBean("MpMapper", MpMapper.class);//加載Mapper

    /*
     * 查詢操作
     * */
    @org.junit.Test
    public void testCommSe() {
        //1.根據ID查詢
//         Mp mp=  mpMapper.selectById(1);
//        System.out.println("根據ID:"+mp);
        //2.多條件查詢
//        Mp mp=new Mp();
//        mp.setId(1);
//        mp.setLastName("超級厲害");
//        Mp mp1=  mpMapper.selectOne(mp);
//        System.out.println(mp1);

        //3.List查詢多條數據
//        List<Integer> list=new ArrayList<Integer>();
//        list.add(1);
//        list.add(2);
//        list.add(3);
//      List<Mp> mps=mpMapper.selectBatchIds(list);
//        System.out.println(mps);

        //4.Map多條件查詢
//        Map<String,Object> map=new HashMap<String, Object>();
//        map.put("id",1);
//        map.put("last_name","超級厲害");
//
//        List<Mp> mps=mpMapper.selectByMap(map);
//        System.out.println(mps);
        //5.分頁查詢
        List<Mp> mps = mpMapper.selectPage(new Page<Mp>(1, 4), null);
        System.out.println(mps);

    }

    /*
     * 根據多條件分頁
     * */
    @org.junit.Test
    public void testWraaper() {

        //分頁多條件差查詢
       /* List<Mp> mps=mpMapper.selectPage(new Page<Mp>(1,2),new EntityWrapper<Mp>()
                .between("age",14,16)
                .eq("gender",1)
                     .eq("last_name","漲漲漲")
        );
        System.out.println(mps);*/
        //根據多條件查詢

        List<Mp> mps = mpMapper.selectList(new EntityWrapper<Mp>()
                .eq("gender", 1)
                .like("last_name", "漲")
                .or()
                .like("email", "m"));
        System.out.println(mps);
    }

    //    多條件修改
    @org.junit.Test
    public void testUpdateWrapper() {
        Mp mp = new Mp();
        mp.setEmail("qweqwe@qq.com");
        int upra = mpMapper.update(mp, new EntityWrapper<Mp>().eq("gender", 0));
        System.out.println("upra------" + upra);
    }

    /*
     * 刪除操作
     * */
    @org.junit.Test
    public void testCommDel() {
        int del = mpMapper.deleteById(1);

        System.out.println("del-----" + del);
    }


    /*
     * 通用更新操作
     * */
    @org.junit.Test
    public void testCommUpdate() {
        Mp mp = new Mp();
        mp.setId(1);
        mp.setLastName("超級厲害");
        mp.setEmail("1111@qq.com");
        mp.setAge(22);
        mp.setGender(2);
        Integer upda = mpMapper.updateById(mp);
        //修改所有
        //  Integer upda=mpMapper.updateAllColumnById(mp);
        System.out.println("修改------" + upda);

    }

    /*
     * 插入操作
     * */
    @org.junit.Test
    public void testCommIns() {
        Mp mp = new Mp();
        mp.setLastName("漲漲漲");
        mp.setEmail("123@qq.com");
        mp.setAge(1);
        mp.setGender(1);
        int add = mpMapper.insert(mp);
        System.out.println("add---" + add);
        System.out.println("獲取自增列:" + mp.getId());
    }

    @org.junit.Test
    public void Show() throws Exception {


        DataSource dataSource = applicationContext.getBean("dataSource", DataSource.class);

        Connection connection = dataSource.getConnection();
        System.out.println("======" + connection);
        System.out.println("---" + dataSource);
    }

}

這就是Mybatis-Plus的最基本的CRUD,謝謝~~~

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM