Article1
一、為什么要有mybatis
mybatis 是一個 Java 的 ORM 框架,ORM 的出現就是為了簡化開發。最初的開發方式是業務邏輯和數據庫查詢邏輯是分開的,或者在程序中編寫 sql 語句,或者調用 sql 存儲過程。這樣導致思維需要在語言邏輯和 sql 邏輯之間切換,導致開發效率低下。所以出現了一系列的 ORM 框架,ORM 框架將數據庫表和 Java 對象對應起來,當操作數據庫時,只需要操作對象的 Java 對象即可,例如設置幾個 and 條件,只需要設置幾個屬性即可。
二、為什么要有mybatis generator
雖然說有了 mybatis 框架,但是學習 mybatis 也需要學習成本,尤其是配置它需要的 XML 文件,那也是相當繁瑣,而且配置中出現錯誤,不容易定位。當出現莫名其妙的錯誤或者有大批量需要生成的對象時,時常會有種生無可戀的感覺在腦中徘徊。故此, mybatis generator 應運而生了。
它只需要簡單配置,即可完成大量的表到 mybatis Java 對象的生成工作,不僅速度快,而且不會出錯,可讓開發人員真正的專注於業務邏輯的開發。
官方提供的 mybatis generator 功能比較簡單,對於稍微復雜但是開發中必然用到的分頁功能、批量插入功能等沒有實現,但已經有成熟的插件功能支持。
我已經將我們平時用的mybatis生成工具放到 github ,其中已集成了分頁、批量插入、序列化功能。可到 這里 查看,已經介紹了使用方法。
三、mybatis generator 生成的文件結構
關於Mybatis-Generator的下載可以到這個地址:https://github.com/mybatis/generator/releases
由於我使用的是Mysql數據庫,這里需要在准備一個連接mysql數據庫的驅動jar包
以下是相關文件截圖:
和Hibernate逆向生成一樣,這里也需要一個配置文件:
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> <!-- 數據庫驅動包位置 --> <classPathEntry location="D:\generator\mysql-connector-java-5.1.34.jar" /> <!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />--> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 數據庫鏈接URL、用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/my_db?characterEncoding=utf8" userId="root" password="123456"> <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">--> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="andy.model" targetProject="D:\generator\src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的映射文件包名和位置 --> <sqlMapGenerator targetPackage="andy.mapping" targetProject="D:\generator\src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="andy.dao" targetProject="D:\generator\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成那些表(更改tableName和domainObjectName就可以) --> <table tableName="kb_city" domainObjectName="KbCity" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> <!-- <table tableName="course_info" domainObjectName="CourseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> <table tableName="course_user_info" domainObjectName="CourseUserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> --> </context> </generatorConfiguration>
生成語句文件:
java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
備注:
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL= 在實際的使用過程中,需要設置utf8格式和時區,需要對“&”進行HTML轉移字符:
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/db_recruit?characterEncoding=utf8&serverTimezone=UTC" userId="root" password="123456">
---------------------
作者:tolcf
來源:CSDN
原文:https://blog.csdn.net/tolcf/article/details/50835165
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
生成的文件包含三類:
- Model 實體文件,一個數據庫表生成一個 Model 實體;
- ModelExample 文件,此文件和實體文件在同一目錄下,主要用於查詢條件構造;
- Mapper 接口文件,數據數操作方法都在此接口中定義;
- Mapper XML 配置文件;
在配置文件中配置好文件的生成路徑,並設置好對應的包名,即可生成對應的目錄結構和文件。我將生成目錄設置為 test 目錄,實體包名設置為 com.fengzheng.dao.entity ,接口包名設置為 com.fengzheng.dao.mapper ,然后生成的文件目錄結構如下圖所示:
四、如何編寫代碼呢
所有的方法調用都來自於生成的接口文件,在 Spring MVC 中,需要在調用方聲明,用一個黑名單接口為例,生成的接口文件為 BlackListIPMapper ,所以在調用方要聲明此接口,如下:
@Autowired private BlackListIPMapper blackListipMapper;
數據庫查詢
查詢是最常用功能,如下方法是查詢 IP 為某值的記錄,如果知道主鍵的話,可以用 selectByPrimaryKey 方法。
public BlackListIP get(String ip){ BlackListIPExample example = new BlackListIPExample(); example.createCriteria().andIpEqualTo(ip); List<BlackListIP> blackListIPList = blackListipMapper.selectByExample(example); if(blackListIPList!=null && blackListIPList.size()>0){ return blackListIPList.get(0); } return null; }
更新、添加、刪除方法調用方法類似,具體可查看相關文檔介紹。
排序
public BlackListIP get(String ip){ BlackListIPExample example = new BlackListIPExample(); example.setOrderByClause("CREATE_TIME desc"); //按創建時間排序 example.createCriteria().andIpEqualTo(ip); List<BlackListIP> blackListIPList = blackListipMapper.selectByExample(example); if(blackListIPList!=null && blackListIPList.size()>0){ return blackListIPList.get(0); } return null; }
分頁
public PageInfo list(Account account, PageInfo pageInfo,String startTime,String endTime) { account.setIsDel(SysParamDetailConstant.IS_DEL_FALSE); AccountExample example = getCondition(account,startTime,endTime); if (null != pageInfo && null != pageInfo.getPageStart()) { example.setLimitClauseStart(pageInfo.getPageStart()); example.setLimitClauseCount(pageInfo.getPageCount()); } example.setOrderByClause(" CREATE_TIME desc "); List<Account> list = accountMapper.selectByExample(example); int totalCount = accountMapper.countByExample(example); pageInfo.setList(list); pageInfo.setTotalCount(totalCount); return pageInfo; }
實現 a=x and (b=xx or b=xxx)這樣的查詢條件
雖然自動生成代碼很方便,但凡事有利即有弊,mybatis generator 沒有辦法生成表聯查(join)功能,只能手動添加。如下實現了a=x and (b=xx or b=xxx)這樣的條件拼接。
AccountExample accountExample = new AccountExample(); AccountExample.Criteria criteria = accountExample.createCriteria().andTypeEqualTo("4"); criteria.addCriterion(String.format(" (ID=%d or ID=%d) ",34,35)); List<Account> accounts = accountMapper.selectByExample(accountExample); return accounts;
但是需要修改一點代碼,修改 org.mybatis.generator.codegen.mybatis3.model包下的ExampleGenerator的第524行代碼,將 method.setVisibility(JavaVisibility.PROTECTED); 改為 method.setVisibility(JavaVisibility.PUBLIC);
改動已同步到github上。
---------------------
作者:風的姿態
來源:博客園
原文:https://www.cnblogs.com/fengzheng/p/5889312.html
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
Article2
MyBatis generator用數據庫表生成數據代碼的時候,除了生成實體的POJO以外,會同時生成Example文件,以及在mapper.xml中生成Example的sql語句。
Example類包含一個內部靜態類 Criteria,利用Criteria我們可以在類中根據自己的需求動態生成sql where字句,不用我們自己再修改mapper文件添加或者修改sql語句了,能節省很多寫sql的時間。
下面將介紹幾種常用的方法(參考上面的博文,這里沒有再總結):
1.模糊搜索用戶名:
String name = “明”; UserExample ex = new UserExample(); ex.createCriteria().andNameLike(’%’+name+’%’); List userList = userDao.selectByExample(ex);
2.通過某個字段排序:
String orderByClause = "id DESC"; UserExample ex = new UserExample(); ex.setOrderByClause(orderByClause); List<User> userList = userDao.selectByExample(ex);
3.條件搜索,不確定條件的個數:
UserExample ex = new UserExample(); Criteria criteria = ex.createCriteria(); if(StringUtils.isNotBlank(user.getAddress())){ criteria.andAddressEqualTo(user.getAddress()); } if(StringUtils.isNotBlank(user.getName())){ criteria.andNameEqualTo(user.getName()); } List<User> userList = userDao.selectByExample(ex);
4.分頁搜索列表:
pager.setPageNum(1); pager.setPageSize(5); UserExample ex = new UserExample(); ex.setPage(pager); List<User> userList = userDao.selectByExample(ex);
---------------------
作者:wkj888888
來源:CSDN
原文:https://blog.csdn.net/wkj888888/article/details/83748886
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!