mybatis generator
简称MBG,是一个专门为mybatis框架使用者定制的代码生成器.可以快速的根据表生成对应的映射文件,接口以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接,存储过程等这些复杂的sql定义需要我们手工编写。
逆向工程配置文件mbg.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="DB2Tables" targetRuntime="MyBatis3">
<!-- 指定如何连接到目标数据库 -->
<jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521:orcl"
userId="scott"
password="123456">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- javaModelGenerator:指定javaBean的生成策略
targetPackage=""目标包名
targetProject=""目标工程 -->
<javaModelGenerator targetPackage="com.atChina.bean"
targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- sqlMapGenerator:sql映射生成策略 -->
<sqlMapGenerator targetPackage="com.atChina.dao"
targetProject=".\conf">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- javaClientGenerator:指定mapper接口所在的位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.atChina.dao"
targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="EMPTEST" domainObjectName="Employee"></table>
<table tableName="DEPTTEST" domainObjectName="Department"></table>
</context>
</generatorConfiguration>
运行逆向生成器生成工程
运行逆向工程,有很多种方式,这里是根据上面配置的xml文件来运行逆向生成器生成工程
@Test
public void testMbg() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.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);
}
测试:
@Test
public void testMybatis3() throws IOException, ParseException{
String resource = "mybatis-config.xml";
InputStream ins = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(ins);
SqlSession openSession = sf.openSession();
try{
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
EmployeeExample example = new EmployeeExample();
Criteria criteria = example.createCriteria();
criteria.andEmpnoLessThan((short)7499);
Criteria criteria2 = example.createCriteria();
criteria2.andJobLike("%ER%");
example.or(criteria2);
List<Employee> emps = mapper.selectByExample(example);
for(Employee em : emps){
System.out.println(em);
}
}finally{
openSession.close();
}
}