mybatis反向工程generatorSqlmap-increase自動生成程式碼,還有一點引數校驗
之前都是大佬搭框架我寫業務程式碼,知道mybatis能自動生成程式碼,但是從來沒自己操作過,菜雞。
一開始我是用springboot的mybatis外掛生成的,但是生成的程式碼裡方法很少,沒有各個欄位的操作,所以又用generatorSqlmap-increase做了一次,生成的程式碼很全,各個欄位,各種條件都可以直接呼叫對應方法,非常簡單好用。
首先搞一份generatorSqlmap-increase的程式碼
大概就是這個樣子。
用IDEA匯入
注意匯入的時候一定要選建立工程,直接匯入會提示無法編譯,標識source和jar包之後能編譯了但是執行還是報錯。
之後就是一路next了,注意libraies選擇的就是專案路徑下的那個lib資料夾。
GeneratorSqlmap類就是啟動的入口。StatisticCodeLines是統計有效程式碼行數的一個工具類,用於檢視生成了多少程式碼。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> <context id="testTables" targetRuntime="MyBatis3"> <!-- 生成批量操作的方法 --> <plugin type="org.mybatis.generator.plugins.batch.BatchInsertPlugin"></plugin> <plugin type="org.mybatis.generator.plugins.batch.BatchUpdatePlugin"></plugin> <!-- JavaBean 實現 序列化 介面 --> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"> </plugin> <!-- genenat 時,生成toString --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin" /> <!-- 自定義物理分頁 可生成支援Mysql資料的limit 不支援Oracle 會在Example類中生成分頁相關的屬性和方法--> <plugin type="org.mybatis.generator.plugins.page.PaginationPlugin" /> <!-- 自定義查詢指定欄位 --> <plugin type="org.mybatis.generator.plugins.field.FieldsPlugin" /> <!-- 開啟支援記憶體分頁 可生成 支援記憶體分佈的方法及引數 <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" /> --> <!-- generate 時,生成hashcode和equals方法 <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" /> --> <!-- 此處是將Example改名為Criteria 當然 想改成什麼都行~ --> <!--<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin"> <property name="searchString" value="Example$" /> <property name="replaceString" value="Query" /> </plugin>--> <!-- 此處是將UserMapper.xml改名為UserDao.xml 當然 想改成什麼都行~ --> <!-- <plugin type="org.mybatis.generator.plugins.rename.RenameSqlMapperPlugin"> <property name="searchString" value="Mapper" /> <property name="replaceString" value="Dao" /> </plugin> --> <!-- 此處是將UserMapper改名為UserDao 介面 當然 想改成什麼都行~ --> <!--<plugin type="org.mybatis.generator.plugins.rename.RenameJavaMapperPlugin"> <property name="searchString" value="Mapper$" /> <property name="replaceString" value="Dao" /> </plugin> --> <!-- 新增@Mapper註解 --> <plugin type="org.mybatis.generator.plugins.annotation.MapperAnnotationPlugin"> <property name="mapperSuffixString" value="Mapper" /> </plugin> <commentGenerator type="org.mybatis.generator.plugins.comment.MyCommentGenerator"> <!-- 是否去除自動生成的註釋 true:是 : false:否 <property name="suppressAllComments" value="true" /> --> </commentGenerator> <!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/demo1" userId="root" password="618033"> </jdbcConnection> <!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把JDBC DECIMAL 和 NUMERIC 型別解析為java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="true" /> </javaTypeResolver> <!-- targetProject:生成PO類的位置 --> <javaModelGenerator targetPackage="com.jia.core.model" targetProject="src"> <!-- enableSubPackages:是否讓schema作為包的字尾 --> <property name="enableSubPackages" value="false" /> <!-- 從資料庫返回的值被清理前後的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper對映檔案生成的位置 --> <sqlMapGenerator targetPackage="mapper" targetProject="src"> <!-- enableSubPackages:是否讓schema作為包的字尾 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper介面生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.jia.core.dao" targetProject="src"> <!-- enableSubPackages:是否讓schema作為包的字尾 --> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 指定資料庫表 --> <table tableName="table1" domainObjectName="Pojo1" ></table> <table tableName="table2" domainObjectName="Pojo2" ></table> <!--SYS_系統配置表 --> <!--<table schema="" tableName="SYS_CONFIG_T" domainObjectName="sys.SysConfig"> <generatedKey column="CONFIG_ID" sqlStatement="Mysql" identity="true"/> <columnOverride column="CONFIG_GROUP" javaType="String" jdbcType="LONGTEXT" /> <columnOverride column="CONFIG_README" javaType="String" jdbcType="LONGTEXT" /> <columnOverride column="CONFIG_VALUE" javaType="String" jdbcType="LONGTEXT" /> </table>--> <!-- 選擇一個table來生成相關檔案,可以有一個或多個table,必須要有table元素 選擇的table會生成以下檔案: 1,SQL map檔案 2,生成一個主鍵類; 3,除了BLOB和主鍵的其他欄位的類; 4,包含BLOB的類; 5,一個使用者生成動態查詢的條件類(selectByExample, deleteByExample),可選; 6,Mapper介面(可選) tableName(必要):要生成物件的表名; 注意:大小寫敏感問題。正常情況下,MBG會自動的去識別資料庫識別符號的大小寫敏感度,在一般情況下,MBG會 根據設定的schema,catalog或tablename去查詢資料表,按照下面的流程: 1,如果schema,catalog或tablename中有空格,那麼設定的是什麼格式,就精確的使用指定的大小寫格式去查詢; 2,否則,如果資料庫的識別符號使用大寫的,那麼MBG自動把表名變成大寫再查詢; 3,否則,如果資料庫的識別符號使用小寫的,那麼MBG自動把表名變成小寫再查詢; 4,否則,使用指定的大小寫格式查詢; 另外的,如果在建立表的時候,使用的""把資料庫物件規定大小寫,就算資料庫識別符號是使用的大寫,在這種情況下也會使用給定的大小寫來建立表名; 這個時候,請設定delimitIdentifiers="true"即可保留大小寫格式; 可選: 1,schema:資料庫的schema; 2,catalog:資料庫的catalog; 3,alias:為資料表設定的別名,如果設定了alias,那麼生成的所有的SELECT SQL語句中,列名會變成:alias_actualColumnName 4,domainObjectName:生成的domain類的名字,如果不設定,直接使用表名作為domain類的名字;可以設定為somepck.domainName,那麼會自動把domainName類再放到somepck包裡面; 5,enableInsert(預設true):指定是否生成insert語句; 6,enableSelectByPrimaryKey(預設true):指定是否生成按照主鍵查詢物件的語句(就是getById或get); 7,enableSelectByExample(預設true):MyBatis3Simple為false,指定是否生成動態查詢語句; 8,enableUpdateByPrimaryKey(預設true):指定是否生成按照主鍵修改物件的語句(即update); 9,enableDeleteByPrimaryKey(預設true):指定是否生成按照主鍵刪除物件的語句(即delete); 10,enableDeleteByExample(預設true):MyBatis3Simple為false,指定是否生成動態刪除語句; 11,enableCountByExample(預設true):MyBatis3Simple為false,指定是否生成動態查詢總條數語句(用於分頁的總條數查詢); 12,enableUpdateByExample(預設true):MyBatis3Simple為false,指定是否生成動態修改語句(只修改物件中不為空的屬性); 13,modelType:參考context元素的defaultModelType,相當於覆蓋; 14,delimitIdentifiers:參考tableName的解釋,注意,預設的delimitIdentifiers是雙引號,如果類似MYSQL這樣的資料庫,使用的是`(反引號,那麼還需要設定context的beginningDelimiter和endingDelimiter屬性) 15,delimitAllColumns:設定是否所有生成的SQL中的列名都使用識別符號引起來。預設為false,delimitIdentifiers參考context的屬性 注意,table裡面很多引數都是對javaModelGenerator,context等元素的預設屬性的一個複寫; --> <!-- 指定資料庫所有表 <table schema="" tableName="%"/> --> <!-- 有些表的欄位需要指定java型別 <table schema="" tableName=""> <columnOverride column="" javaType="" /> </table> --> </context> </generatorConfiguration>
注意context標籤中的標籤順序是不能變的,變了之後會報錯,鬱悶。
生成程式碼的標籤的targepProjet屬性寫src,生成的程式碼就會生成在src下面,如圖
xml檔案
裡面定義著住的欄位的型別和各個方法的sql。
dao接口裡就是對應的方法。
模型包下就是一個model類對應一個model的Example類,用於查詢。
然後寫控制器
@Controller public class GoodsController { @Autowired private GoodsService goodsService; @RequestMapping(value = "/goods/list", method = RequestMethod.POST) @ResponseBody public JsonResultObject<Object> goodsList(@RequestBody @Valid GoodsListParam param, Errors errors, HttpServletRequest request) { JsonResultObject<Object> resultJson = new JsonResultObject<>(); if (errors.hasErrors()) { List<ObjectError> errorList = errors.getAllErrors(); for (ObjectError error : errorList) { resultJson.setInfo(error.getDefaultMessage() + " "); } resultJson.setCode(HttpStatus.業務處理失敗.getValue()); return resultJson; } //具體的操作,呼叫service層的方法 }
用@Controller標記控制器,注入service層的例項。上面@RequestBody @Valid(這個是javax.validation.Valid)標記的引數是從前端或者並且校驗的,如果校驗有錯誤,錯誤會被放到Errors物件中(這個是org.springframework.validation.Errors,和org.springframework.validation.BindingResult一樣的功能,網上搜BindingResult能搜到很多,但是搜Errors很少,BindingResult是繼承Errors的),在GoodsListParam物件中,在屬性上用註解就可以定義校驗規則。
校驗註解org.hibernate包下的和javax.validation包下的好像都可以用。
JsonResultObject物件是一個用於給前端返回資料的資料物件,這樣的話保證了給前端返回資料的格式一致性。
之後再寫service層的程式碼
@Service("goodsService")
@Transactional(rollbackFor = Exception.class)
public class GoodsServiceImpl implements GoodsService {
@Autowired
private SaleUnitDao saleUnitDao;
//其他屬性和方法
}
把dao層介面例項注入進來,上面生成的程式碼是Mapper結尾的,這個是改成Dao結尾的,總之就是dao介面。
貼一個sevice層的方法
@Override
public ServiceResult routeTicketsDetail(QueryRouteDetailParam param) {
ServiceResult result = new ServiceResult();
/**
* 查詢門票
*/
SaleUnitQuery query = new SaleUnitQuery();
query.createCriteria().andRefBizIdEqualTo(param.getLineId())
.andSaleStatusEqualTo(EumGoods.SaleUnitStatus.啟用.getValue())
.andBizTypeEqualTo(EumGoods.SaleUnitBizType.線路門票.getValue()).andDeleteFlagEqualTo(DeleteFlag.未刪除.getValue());
List<SaleUnit> saleUnitList = saleUnitDao.selectByExample(query);
if (!ListUtil.isValidateList(saleUnitList)) {
result.setResult(false);
result.setInfo("門票不存在");
return result;
}
result.setData(saleUnitList.get(0));
result.setInfo("獲取資料正常");
result.setResult(true);
return result;
}
SaleUnitQuery就是和實體類一起生成的Example類,這裡是把字尾Example改成了Query,然後調這個物件的createCriteria()方法,然後在後面追加條件即可,然後呼叫dao介面的selectByExample方法返回資料。