zoukankan      html  css  js  c++  java
  • Mybatisplus快速入门 小毛毛

    简介

    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,谢谢~~~

    
    
  • 相关阅读:
    [C#] 多线程总结(结合进度条)
    [Winform] DataGridView 中 DataGridViewComboBox 的可编辑
    [Tool] 仿博客园插入代码的 WLW 插件
    [C#] 获取打印机列表
    [Access] C# 通过 COM 组件访问 Access 文件
    [Excel] 打印设置
    [Q&A] 应用程序清单生成失败
    [Excel] Worksheet.PasteSpecial
    canvas裁剪图片,纯前端
    javascript将base64编码的图片数据转换为file并提交
  • 原文地址:https://www.cnblogs.com/zgwjava/p/10091435.html
Copyright © 2011-2022 走看看