MyBatis Generator的详细介绍http://mybatis.github.io/generator/index.html
MyBatis Generator With Maven http://mybatis.github.io/generator/running/runningWithMaven.html
1前言
前段时间根据工作需要,使用Spring+Mybatis完成了一个功能模块,领导推荐了MyBatis Generator(以下简称为MBG),可以逆向生成持久层的基本代码,而且mybatis的实现方案比较好,可以自由组合完成比较复杂的查询,当然更复杂的就需要手动写了,下面整理下基本使用
2搭建逆向工程
1.创建一个Maven项目:File——New Project——Maven
2.在pom文件中,添加MBG插件,IDE会自动帮我们下载插件
(如果没反应,可以点开右侧Maven Project选项卡刷新以下)
<build>
<finalName>mybatis_generator</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
</plugin>
</plugins>
</build>
3.在src/main/resource目录下创建generatorConfig.xml文件
(官方配置以及说明:http://mybatis.github.io/generator/configreference/xmlconfig.html)
<?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>
<!--数据库驱动jar -->
<classPathEntry location="E:\mysql-connector-java-5.1.7-bin.jar" />
<context id="DB2Tables" targetRuntime="Ibatis2Java5">
<!--去除注释 (true好像不起作用) -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/news"
userId="root"
password="">
</jdbcConnection>
<!--默认false
Java type resolver will always use java.math.BigDecimal if the database column is of type DECIMAL or NUMERIC.
-->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建 使用Maven生成在target目录下,会自动创建) -->
<javaModelGenerator targetPackage="com.qianyan.model" targetProject="MAVEN">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--生成SQLMAP文件 -->
<sqlMapGenerator targetPackage="com.qianyan.persistence.ibatis" targetProject="MAVEN">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!--生成Dao文件 可以配置 type="XMLMAPPER"生成xml的dao实现 context id="DB2Tables" 修改targetRuntime="MyBatis3" -->
<javaClientGenerator type="SPRING" targetPackage="com.qianyan.persistence.dao" targetProject="MAVEN">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!--对应数据库表 mysql可以加入主键自增 字段命名 忽略某字段等-->
<table tableName="USER" domainObjectName="User" >
</table>
</context>
</generatorConfiguration>
4.点击Maven Project——项目——Plugins——mybatis generator——Run Maven build
5.可以根据自己项目的配置,把生成的代码拷贝到自己的项目中去
3生成代码的使用
mybatis设计比较巧妙,Dao层就不用说了,这里主要介绍下实体类User和UserExample
User类就是普通的实体类,定义了数据库对应的字段,以及set/get方法
Example类是干嘛的呢?用其它项目中的几个例子还说明一下吧
1.比如在一个项目 我们要删除某个小组下某个用户的信息
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);
}
2.根据小组ID(非主键 更新小组信息)
public int updateStudyTeamInfo(StudyTeamInfo st){
StudyTeamInfoExample ste = new StudyTeamInfoExample();
ste.createCriteria().andTeamIdEqualTo(st.getTeamId());
return studyTeamInfoDAO.updateByExampleSelective(st,ste);
}
3.(1)模糊查询并且排序 (2)大于等于某个分数 并且小于某个分数的查询
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;
}
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;
}
Example中提供了Critertia,一种面向对象的查询方式,并且根据实体类中字段的属性,生成不同的操作。
当然你也可以根据实际需要直接使用实体类进行增删改查。
4一些问题的解决方案
在实际应用中,自己也遇到了一些问题,下面是这些问题的解决方案,欢迎提供更好的方法
1.字段默认值问题
在数据库中,一些字段有默认值,比如c_time,我们在insert操作时,不需要这个字段
public void saveUserStudyTeamApplyInfo(StudyTeamUserApplyInfo uai){
long ref = studyTeamInfoDAO.getSeqAllRef();
uai.setRef(new BigDecimal(ref));
studyTeamUserApplyInfoDAO.insertSelective(uai);
}
2.分页问题
mybatis没有提供分页的解决方法,可能是因为数据库之间分页的差距比较大
通过修改java代码只能做到内存分页,所以还是需要在sqlmap中添加数据库分页
参考了网上某篇博客的解决方法(地址找不到了),加了分页头和分页尾的,这样只用写内部的sql
可以一定程度下减少错误几率
<!-- oracle 分页头 -->
<sql id="oracle_Pagination_Head" >
<dynamic >
<isNotEmpty property="first" >
<isNotEmpty property="last" >
<![CDATA[select * from ( select row_.*, rownum rownum_ from ( ]]>
</isNotEmpty>
</isNotEmpty>
</dynamic>
</sql>
<!-- oracle 分页尾 -->
<sql id="oracle_Pagination_Tail" >
<dynamic >
<isNotEmpty property="first" >
<isNotEmpty property="last" >
<![CDATA[) row_ where rownum <= #last# ) where rownum_ > #first#]]>
</isNotEmpty>
</isNotEmpty>
</dynamic>
</sql>
<select id="findAllStudyTeamMessagePage" parameterClass="java.util.Map" resultMap="ResultMapWithUserName">
<!-- 增加oracle分页头部 -->
<include refid="oracle_Pagination_Head" />
select a.*,b.user_name,b.photo_name, rownum rn,sysdate
from user_info b,study_team_user_message a
where b.user_id=a.user_id
and type=0
<isNotEqual prepend="and" property="team_id" compareValue="0">
a.team_id=#team_id#
</isNotEqual>
order by a.ref desc
<include refid="oracle_Pagination_Tail" />
</select>
3.mysql text字段无法识别问题
<!--对应数据库表 mysql可以加入主键自增 字段命名 忽略某字段等-->
<table tableName="article" domainObjectName="Article" >
<columnOverride column="content" jdbcType="VARCHAR" />
</table>
下载:GIT@OSC http://git.oschina.net/lujianing/Mybatis_Generator
ps:2014-3-28
公司用的是ibatis2.3.x 所以使用的
<context id="DB2Tables" targetRuntime="Ibatis2Java5">
http://mybatis.github.io/generator/configreference/javaClientGenerator.html如果使用 type=XMLMAPPER (xml直接实现dao)
需要targetRuntime is MyBatis3 而且不向下兼容