真赞!IDEA中这么玩MyBatis,让编码速度飞起!

点击上方 "程序员小乐"关注, 星标或置顶一起成长

每天凌晨00点00分, 第一时间与你相约

每日英文

The greatest measure of success in life isn’t how much money you make. It’s whether or not you’re able to lead the life you want to live.

生活中,衡量成功与否的最好标准并不是你挣了多少钱,而是你是否能过上你想过的生活。

每日掏心

我想刷新自己的思维,删除自己的毛病,撤销犯下的错误,保存所有欢乐的时光。

来自:Orson | 责编:乐乐

链接:cnblogs.com/java-class/p/6237564.html

程序员小乐(ID:study_tech) 第 915 次推文  图源:百度

往日回顾:程序员在地铁上写代码被路人吐槽:有什么好装的!网友评论炸锅了!

     

   正文   

IDEA 逆向 MyBatis 工程时,不像支持 Hibernate 那样有自带插件,需要集成第三方的 MyBatis Generator。

MyBatis Generator的详细介绍 http://mybatis.github.io/generator/index.html

本篇博客图解 MyBatis Generator 的使用过程,并结合实战说明逆向工程的使用方式。

# 搭建 MyBatis Generator 插件环境

a. 添加插件依赖 pom.xml

<!--mybatis 逆向生成插件-->
<plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.3.2</version>
     <configuration>
        <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
     </configuration>
     <executions>
        <execution>
           <id>Generate MyBatis Artifacts</id>
        </execution>
     </executions>
     <dependencies>
        <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.2</version>
        </dependency>
     </dependencies>
</plugin>

b.配置文件 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"/>
    <classPathEntry location="${jdbc_driverLocation}"/>
  <!--指定特定数据库的jdbc驱动jar包的位置-->


    <context id="default" targetRuntime="MyBatis3">
        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>


        <!--jdbc的数据库连接 -->
        <jdbcConnection
                driverClass="${jdbc_driverClass}"
                connectionURL="${jdbc_url}"
                userId="${jdbc_user}"
                password="${jdbc_pwd}">
        </jdbcConnection>


        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver><property name="forceBigDecimals" value="false"/></javaTypeResolver>


        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <javaModelGenerator targetPackage="com.rambo.sdm.dao.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"/>
        </javaModelGenerator>


        <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <sqlMapGenerator targetPackage="com.rambo.sdm.dao.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>


        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator targetPackage="com.rambo.sdm.dao.inter" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <table tableName="user" domainObjectName="UserPO">
            <generatedKey column="uuid" sqlStatement="SELECT REPLACE(UUID(),'-','') UUID FROM DUAL"/>
        </table>
    </context>
</generatorConfiguration>

c.数据库配置文件 jdbc.properties

jdbc_driverLocation=D:\\Program Files\\Repository\\mysql\\mysql-connector-java\\5.1.38\\mysql-connector-java-5.1.38.jar
jdbc_driverClass=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&amp;characterEncoding=utf-8
jdbc_user=root
jdbc_pwd=123456
validationQuery = select 1

d. 配置插件启动项

# 项目实战

User类就是普通的实体类,定义了数据库对应的字段,以及set/get方法。

Mybatis 引入了 Example 类,用来封装数据库查询条件。

a.比如在一个项目 我们要删除某个小组下某个用户的信息

public int deleteUserApplyInfo(long user_id,long team_id){
        StudyTeamUserApplyInfoExample ue = new StudyTeamUserApplyInfoExample();
        ue.createCriteria().andUserIdEqualTo(new BigDecimal(user_id)).andTeamIdEqualTo(new BigDecimal(team_id));
        return studyTeamUserApplyInfoDAO.deleteByExample(ue);
}

b.根据小组ID(非主键 更新小组信息)

public int updateStudyTeamInfo(StudyTeamInfo st){
        StudyTeamInfoExample ste = new StudyTeamInfoExample();
        ste.createCriteria().andTeamIdEqualTo(st.getTeamId());
        return studyTeamInfoDAO.updateByExampleSelective(st,ste);
}

c.其它

(1)模糊查询并且排序 

public List<StudyTeamInfo> getStudyTeamInfoByName(String team_name){
        StudyTeamInfoExample se = new StudyTeamInfoExample();
        se.createCriteria().andTeamNameLike("%"+team_name+"%").andEnableEqualTo((short)1);
        se.setOrderByClause("team_score desc");
        List<StudyTeamInfo> ls = studyTeamInfoDAO.selectByExample(se);
        if(ls!=null&&ls.size()>0){
            return ls;
        }
        return null;
    }

(2)大于等于某个分数 并且小于某个分数的查询

public StudyTeamLevel getStudyTeamLevel(long score){
        StudyTeamLevelExample le = new StudyTeamLevelExample();
        le.createCriteria().andNeedScoreLessThanOrEqualTo(score).andUpScoreGreaterThan(score);
        List<StudyTeamLevel> ls = studyTeamLevelDAO.selectByExample(le);
        if(ls!=null&&ls.size()>0){
            return ls.get(0);
        }
        return null;
}

欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,欢迎转发分享给更多人。欢迎加入程序员小乐技术交流群,在后台回复“加群”或者“学习”即可。

猜你还想看

阿里、腾讯、百度、华为、京东最新面试题汇集

一文带你了解 MySQL 中的各种锁机制!

分布式锁用 Redis 还是 Zookeeper?看完你就明白了!

Class.forName 和 ClassLoader 到底有啥区别?

关注订阅号「程序员小乐」,收看更多精彩内容

嘿,你在看吗

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值