MyBatis Generator的詳細介紹http://mybatis.github.io/generator/index.html html
MyBatis Generator With Maven http://mybatis.github.io/generator/running/runningWithMaven.html java
前段時間根據工做須要,使用Spring+Mybatis完成了一個功能模塊,領導推薦了MyBatis Generator(如下簡稱爲MBG),能夠逆向生成持久層的基本代碼,並且mybatis的實現方案比較好,能夠自由組合完成比較複雜的查詢,固然更復雜的就須要手動寫了,下面整理下基本使用mysql
1.建立一個Maven項目:File——New Project——Mavengit
2.在pom文件中,添加MBG插件,IDE會自動幫咱們下載插件github
(若是沒反應,能夠點開右側Maven Project選項卡刷新如下)sql
(插件1.3.0有點小bug,不能去掉生成的註釋)數據庫
<build> <finalName>mybatis_generator</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> </plugin> </plugins> </build>
3.在src/main/resource目錄下建立generatorConfig.xml文件 mybatis
(官方配置以及說明:http://mybatis.github.io/generator/configreference/xmlconfig.html) oracle
<?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"> <!--去除註釋 --> <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
dom
5.能夠根據本身項目的配置,把生成的代碼拷貝到本身的項目中去
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,一種面向對象的查詢方式,而且根據實體類中字段的屬性,生成不一樣的操做。
固然你也能夠根據實際須要直接使用實體類進行增刪改查。
在實際應用中,本身也遇到了一些問題,下面是這些問題的解決方案,歡迎提供更好的方法
1.字段默認值問題
在數據庫中,一些字段有默認值,好比c_time,咱們在insert操做時,不須要這個字段
public void saveUserStudyTeamApplyInfo(StudyTeamUserApplyInfo uai){ long ref = studyTeamInfoDAO.getSeqAllRef(); uai.setRef(new BigDecimal(ref)); studyTeamUserApplyInfoDAO.insertSelective(uai); }
能夠調用insertSelective方法,傳入實體類,方法會根據實體類中存在值的字段動態拼接sql
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">
<javaClientGenerator type="SPRING"
若是使用 type=XMLMAPPER (xml直接實現dao)
須要targetRuntime is MyBatis3 並且不向下兼容
http://mybatis.github.io/generator/configreference/javaClientGenerator.html
2014-9-15
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.0</version> <dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.2.0</version> </dependency> </dependencies> </plugin>
在pom中能夠直接配置依賴的數據庫 generatorConfig.xml就不須要再配置數據庫的jar了