Mybatis常用插件

1.mybatis-generator

  作用:根据数据库自动生成pojo、dao和xml文件。

  1.导入依赖和maven插件

 <!--mybatis逆向工程依赖-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>
<!--逆向工程插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!--允许移动生成的文件-->
                    <verbose>true</verbose>
                    <!--允许覆盖生成的文件-->
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <!--<scope>runtime</scope>-->
                        <version>5.1.41</version>
                    </dependency>
                </dependencies>
            </plugin>

 2.resources下生成generatorConfig.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!--导入属性配置-->
    <properties resource="jdbc.properties"></properties>
    <!-- 指定特定数据库的jdbc驱动jar包的位置 -->
   <!-- <classPathEntry location="${db.driverLocation}"/>-->
    <!--
        context:至少需要有一个<context>元素,用于指定一组对象的环境。
        必选属性:id:用来确定一个<context>元素
        可选属性:
        1、defaultModelType:**这个属性很重要**,这个属性定义了MBG如何生成**实体类**。

            conditional 默认属性,这个模型和下面的hierarchical类似,除了如果那个单独的类将只包含一个字段,
                        将不会生成一个单独的类。因此,如果一个表的主键只有一个字段,那么不会为该字段生成单独的实体类,
                        将该字段合并到基本实体类中。
            flat:该模型为每一张表只生成一个实体类。这个实体类包含表中的所有字段。**这种模型最简单,推荐使用。
            hierarchical:如果表有主键,那么该模型会产生一个单独的主键实体类,如果表还有BLOB字段,
                        则会为表生成一个包含所有BLOB字段的单独的实体类,
                       然后为所有其他的字段生成一个单独的实体类。 MBG会在所有生成的实体类之间维护一个继承关系。
        2、targetRuntime::此属性用于指定生成的代码的运行时环境。一般使用默认值即可。
                MyBatis3:*这是默认值*
                MyBatis3Simple
                Ibatis2Java2
                Ibatis2Java5
    -->
    <context id="context" defaultModelType="conditional" targetRuntime="MyBatis3">
        <!--旨在创建class时,对注释进行控制-->
        <commentGenerator>
            <!--suppressAllComments  false时打开注释,true时关闭注释-->
            <property name="suppressAllComments" value="false"/>
            <!--suppressDate  false时打开时间标志,true时关闭-->
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}"/>
        <!--java类型处理器
            用于处理DB中的类型到Java中的类型,默认使用JavaTypeResolverDefaultImpl;
            注意一点,默认会先尝试使用Integer,Long,Short等来对应DECIMAL和 NUMERIC数据类型;
        -->
        <javaTypeResolver>
            <!--
            true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型
            false:默认,
                scale>0;length>18:使用BigDecimal;
                scale=0;length[10,18]:使用Long;
                scale=0;length[5,9]:使用Integer;
                scale=0;length<5:使用Short;
            -->
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>
        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <javaModelGenerator targetPackage="com.wx.pojo"
                            targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
            <!-- 设置一个根对象,即基类-->
            <property name="rootClass" value="com.wx.pojo.BaseEntity"/>
        </javaModelGenerator>

        <!--Mapper映射文件生成器
            targetPackage:指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <sqlMapGenerator targetPackage="com.wx.mapper"
                         targetProject="src/main/java">
            <!--是否允许子包,即targetPackage.schemaName.tableName-->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 对于mybatis来说,即生成Mapper接口
            targetPackage/targetProject:同javaModelGenerator
            type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):
                1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),
                不会生成对应的XML;
                2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中;
                3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML;
            注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
        -->
        <javaClientGenerator targetPackage="com.wx.mapper"
                             targetProject="src/main/java"
                             type="XMLMAPPER">
            <!--是否允许子包,即targetPackage.schemaName.tableName-->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!--
            tableName:数据库表名
            domainObjectName:实体类名
            enableCountByExample(默认true):MyBatis3Simple为false,
                指定是否生成动态查询总条数语句(用于分页的总条数查询);
            enableUpdateByExample:(默认true):MyBatis3Simple为false,
                指定是否生成动态修改语句(只修改对象中不为空的属性);
            enableDeleteByExample:enableDeleteByExample(默认true):
                MyBatis3Simple为false,指定是否生成动态删除语句;
            enableSelectByExample:enableSelectByExample(默认true):
                MyBatis3Simple为false,指定是否生成动态查询语句;
            selectByExampleQueryId:
            enableInsert(默认true):指定是否生成insert语句;
            enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get);
            enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update);
            enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete);
            modelType:参考context元素的defaultModelType,相当于覆盖;
        -->
        <table tableName="actor"
               domainObjectName="Actor"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false"/>
        <!-- 指定数据库表 -->
        <table tableName="address" domainObjectName="Address"></table>
        <table tableName="city" domainObjectName="City"></table>
        <table tableName="country" domainObjectName="Country"></table>
        <table tableName="customer" domainObjectName="Customer"></table>
        <table tableName="film" domainObjectName="Film"></table>
        <table tableName="film_actor" domainObjectName="Film_actor" ></table>
        <table tableName="film_category" domainObjectName="Film_category"></table>
        <table tableName="film_text" domainObjectName="Film_text"></table>
        <table tableName="inventory" domainObjectName="Inventory"></table>
        <table tableName="items" domainObjectName="Items"></table>
        <table tableName="language" domainObjectName="Language"></table>
        <table tableName="orderdetail" domainObjectName="Orderdetail"></table>
        <table tableName="orders" domainObjectName="Orders"></table>
        <table tableName="payment" domainObjectName="Payment"></table>
        <table tableName="rental" domainObjectName="Rental" ></table>
        <table tableName="staff" domainObjectName="Staff"></table>
        <table tableName="store" domainObjectName="Store"></table>
        <table tableName="user" domainObjectName="User"></table>
    </context>
</generatorConfiguration>

 双击他执行:

 

 生成pojo,mapper接口和mapper.xml

2.代码的使用,这个逆向工程其实最主要就是拿来生成一下实体类,其他的都不用

查询

首先说一下查询的不足之处:不能指定查询的列,只能够查询所有列。

我们可以看到,有三个查询方法(一般来说只有两个查询方法,第二个查询方法只会在特定条件下出现)

方法1:selectByExample(TbItemDescExample  example)        

返回值:List<TbItemDesc>

作用:通过特定限制条件查询信息,example用于生成一个Criteria对象来设置查询条件
 

TbItemDescExample example = new TbItemDescExample();
cn.e3mall.pojo.TbItemDescExample.Criteria criteria = example.createCriteria();
long minId = 0;
long maxId = 50;
criteria.andItemIdBetween(minId, maxId); // 设置条件:ItemId在 0 和 50 之间
		
List<Long> ids = new ArrayList<>();
ids.add((long)20);
ids.add((long)40);
ids.add((long)60);
criteria.andItemIdIn(ids);	// 设置条件:ItemId等于 20 或 40 或 60
		
criteria.andCreatedIsNotNull(); // 设置条件:Created列属性不为空
		
long id = 40;
criteria.andItemIdEqualTo(id); // 设置条件:ItemId等于40
		
// 执行查询
List<TbItemDesc> selectByExample = itemDescMapper.selectByExample(example);

方法2:selectByPrimaryKey(Long  itemId)        

返回值:TbItemDesc

作用:通过主键查询

方法3:selectByExampleWithBLOBs(TbItemDescExample  example)

返回值:List<TbItemDesc>

作用:根据特定限制条件查询,返回值包含类型为text的列(默认查询并不会返回该列的信息)。example用于生成一个Criteria对象来设置查询条件,具体使用方法和方法1是一样的,唯一的把不同就是返回值是所有列。
 

2.mybatis-plugin

这是一个能够追踪dao 接口和mapper文件里xml的一个插件

  • 编辑XML时自动补全
  • 根据Mapper接口,使用快捷键生成xml文件及SQL标签
  • ResultMap中的property支持自动补全
  • 快捷键生成@Param注解
  • XML中编辑SQL时, 括号自动补全
  • XML中编辑SQL时, 支持参数自动补全(基于@Param注解识别参数)
  • 自动检查Mapper XML文件中ID冲突
  • 自动检查Mapper XML文件中错误的属性值
  • 支持Find Usage
  • 支持重构从命名
  • 支持别名
  • 自动生成ResultMap属性
  • 快捷键: Alt + Enter(Windows)

装好之后可以这样来回切换

3.分页插件mybatis-pagehelper的使用

 添加依赖:

<!-- 添加分布插件的包pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.0.0</version>
        </dependency>

 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="lazyLoadingEnabled" value="true"></setting>
        <!-- 按需加载: false:使用关联属性,及时加载;    true,加载对象,则加载所有属性, -->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

    <!-- 配置分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>

</configuration>

 Spring中加载配置:

 使用:

Integer pageNum = geoFenceQueryParam.getPageNum()!=null?geoFenceQueryParam.getPageNum():1;
            Integer pageSize = geoFenceQueryParam.getPageSize()!=null?geoFenceQueryParam.getPageSize():10;
            Page page = PageHelper.startPage(pageNum, pageSize, true);
            List<GeoFence> list = moonlightMapper.queryGeoFence(geoFenceQueryParam);

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时空恋旅人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值