[toc]
概述
- 官網(wǎng)提供的mapper自動生成工具mybatis-generator-core-1.3.6.jar
- 可以生成 po類,mapper映射文件,mapper接口
- 支持單表查詢(簡單查詢,條件查詢,1.3.6提供動態(tài)sql)
- 官網(wǎng)MyBatis Generator使用文檔:http://www.mybatis.org/generator/index.html
mybatis-generator逆向工程
如何搭建
-
jar包
- log4j
- mybatis核心
- mybatis-generator-core-1.3.6.jar
- 數(shù)據(jù)庫連接jar
-
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"> <commentGenerator> <!-- 是否 去除自動生成的注釋 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--數(shù)據(jù)庫連接 信息--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://10.211.55.6:3306/mybatis?characterEncoding=utf-8" userId="machine" password="4869"> </jdbcConnection> <!-- 如使用oracle參考如下 --> <!-- <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:orcl" userId="scott" password="wcy675600920"> </jdbcConnection> --> <!-- false(默認): 把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer, true: 把JDBC DECIMAL 和 NUMERIC 類型解析為java.math.BigDecimal --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--targetProject: 生成 PO類 的位置--> <!-- mac下路徑是./src windows 路徑是.\src --> <javaModelGenerator targetPackage="com.machine.pro.pojo" targetProject="./src"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> <!-- 從數(shù)據(jù)庫返回的值 被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject: 生成 mapper映射文件 的位置 --> <sqlMapGenerator targetPackage="com.machine.pro.mapper" targetProject="./src"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.machine.pro.mapper" targetProject="./src"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!--指定要生成的 數(shù)據(jù)庫表--> <table tableName="user" /> <table tableName="orders" /> <!--table更多細節(jié)--> <!-- <table tableName="" domainObjectName=""> <columnOverride column="" javaType="" /> </table> --> </context> </generatorConfiguration> -
GeneratorSqlMap.java
public class GeneratorSqlMap { public void generator() throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; //指定逆向工程配置文件 File configFile = new File("config/generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } public static void main(String[] args) { try { GeneratorSqlMap generator = new GeneratorSqlMap(); generator.generator(); } catch (Exception e) { e.printStackTrace(); } } } 運行main可生成相應代碼
附錄:我的代碼地址
https://github.com/Machine4869/MyCode/tree/master/Mybatis逆向工程/
一些映射 生成規(guī)則
- 如表的creat_time字段 會映射成 pojo的craeteTime屬性(去下劃線大寫)
- user表 會映射成 User類
- tb_user表會映射成 TbUser類
Mapper接口測試與使用
(法一)采用Example進行條件查詢
配置:targetRuntime="MyBatis3"
<context id="testTables" targetRuntime="MyBatis3">
常用接口
//按id 查詢
UserselectByPrimaryKey(String id);
//按id 刪除
int deleteByPrimaryKey(String id);
//按id 更新:對象中所有字段
int updateByPrimaryKey(User record);
//按id 更新:對象中非空字段
int updateByPrimaryKeySelective(User record);
//插入對象 所有字段
// :insert into user(id,username,sex....) values..
int insert(User record);
//插入對象 非空字段
// :insert into user(username) values..
int insertSelective(User record);
//按條件 刪除
int deleteByExample(UserExample example);
//按條件 查詢 結果集
List<User> selectByExample(UserExample example);
條件查詢:
@Test
public void test3(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//查詢所有
/*
UserExample userExample = null;
List<User> userList = userMapper.selectByExample(userExample);
*/
//單條件查詢
/*
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUsernameLike("%m%");
List<User> userList = userMapper.selectByExample(userExample);
*/
//多條件查詢and
/*
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUsernameLike("%m%");
criteria.andSexEqualTo("女");
List<User> userList = userMapper.selectByExample(userExample);
*/
//多條件查詢or
/*
UserExample userExample = new UserExample();
UserExample.Criteria criteria1 = userExample.createCriteria();
criteria1.andUsernameLike("%m%");
UserExample.Criteria criteria2 = userExample.createCriteria();
criteria2.andSexEqualTo("女");
userExample.or(criteria1);
userExample.or(criteria2);
List<User> userList = userMapper.selectByExample(userExample);
*/
//排序
/*
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUsernameLike("%m%");
//userExample.setOrderByClause("id asc");//asc:正序排 desc:逆序排
//userExample.setOrderByClause("id desc");
userExample.setOrderByClause("sex asc,username asc");
List<User> userList = userMapper.selectByExample(userExample);
*/
//統(tǒng)計
/*
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUsernameLike("%m%");
criteria.andIdBetween(1,5);//包括1和5
long count = userMapper.countByExample(userExample);
*/
}
(法二)MyBatis Dynamic SQL(用where子句進行條件查詢)
-
概述:
- generator 使用為MyBatis3DynamicSQL生成代碼,這些類依賴于MyBatis Dynamic SQL
- MyBatis Dynamic SQL 是生成動態(tài) SQL 語句的框架,可以配合為MyBatis Generator使用
- MyBatis Dynamic SQL 使用WHERE子句(可以用任意組合的and和or來創(chuàng)建)進行條件查詢
- MyBatis Dynamic SQL lib下載地址
-
準備工作
-
jar包 :mybatis-dynamic-sql-1.0.0.jar
-
配置:targetRuntime="MyBatis3"
<context id="testTables" targetRuntime="MyBatis3DynamicSQL">
-
使用:
前提:import靜態(tài)支持類
import static com.machine.pro.mapper.UserDynamicSqlSupport.*; // import 自動生成的 "support" 類
import static org.mybatis.dynamic.sql.SqlBuilder.*; // import MyBatis Dynamic SQL where support
使用案例:
@Test
public void test2(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
/**
* MyBatis Dynamic SQL
* build():所有構建器都通過調(diào)用build()方法完成
* execute():調(diào)用execute方法執(zhí)行語句
*/
//按主鍵查詢 仍然可用
/*
User user = userMapper.selectByPrimaryKey(3);
*/
//查詢所有(不用where子句)
/*
List<User> userList = userMapper.selectByExample()
.build().execute();
*/
//單條件查詢
/*
List<User> userList = userMapper.selectByExample()
.where(sex, isEqualTo("女"))
.build().execute();
//如sex屬性就來自import static 的支持類
*/
//多條件查詢and
/*
List<User> userList = userMapper.selectByExample()
.where(sex, isEqualTo("女"))
.and(username, isLike("%m%"))
.build().execute();
*/
//多條件查詢or
/*
List<User> userList = userMapper.selectByExample()
.where(sex, isEqualTo("女"))
.or(username, isLike("%m%"))
.build().execute();
*/
//排序:正序
/*
List<User> userList = userMapper.selectByExample()
.where(username, isLike("%m%"))
.orderBy(id)
.build().execute();
*/
//排序:逆序
/*
List<User> userList = userMapper.selectByExample()
.where(username, isLike("%m%"))
.orderBy(id.descending())
.build().execute();
*/
//排序:多字段
/*
List<User> userList = userMapper.selectByExample()
.where(username, isLike("%m%"))
.orderBy(sex.descending(),username)
.build().execute();
*/
//統(tǒng)計
/*
Long count = userMapper.countByExample()
.build().execute();
*/
}
注意事項
Mapper文件內(nèi)容不覆蓋而是追加
- XXXMapper.xml文件已經(jīng)存在時,如果進行重新生成則mapper.xml文件內(nèi)容不被覆蓋而是進行內(nèi)容追加,結果導致mybatis解析失敗。
- 解決方法:刪除原來已經(jīng)生成的mapper xml文件再進行生成。