Mybatis(八)逆向工程
mybaits需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java,mapper.xml、pojo等)有了sql表的结构后, 我们就可以利用逆向工程直接生成相应的Dao和JavaBean代码, 以及mapper.xml文件,这样能够大大减少我们平时开发的工作量。 但是使用逆向工程局限性, 逆向工程方法只能执行一次, 如果再次执行就会继续生成相应的Dao和JavaBean, 除非我们把之前生成的全都删除。这样对于代码的扩展性就不是很好, 如果我们需要对表结构进行修改, 那么我们就必须对生成的Dao和JavaBean进行一个个修改,或者重新生成一份。
MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、 存储过程等这些复杂sql的定义需要我们手工编写。
文档查阅:
http://www.mybatis.org/generator/
官网下载:
https://github.com/mybatis/
下载步骤如下:
使用步骤:
1、导入相关的jar包:这里支持mysql,oracl
2、编写MBG的配置文件(重要几处配置)
1)jdbcConnection配置数据库连接信息
2)javaModelGenerator配置javaBean的生成策略
3)sqlMapGenerator 配置sql映射文件生成策略
4)javaClientGenerator配置Mapper接口的生成策略
5)table 配置要逆向解析的数据表(tableName:表名,domainObjectName:对应的javaBean名)
运行代码生成器生成代码注意Context标签,targetRuntime=“MyBatis3“可以生成带条件的增删改查,targetRuntime=“MyBatis3Simple“可以生成基本的增删改查,如果再次生成,建议将之前生成的数据删除,避免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> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.61.22:3306/test" userId="root" password="123456"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成PO类的位置 --> <javaModelGenerator targetPackage="com.softjx.model" targetProject=".\src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.softjx.dao" targetProject=".\src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.softjx.dao" targetProject=".\src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定数据库表 --> <table schema="test" tableName="school" domainObjectName="School"></table> <table schema="test" tableName="student" domainObjectName="Student"></table> </context> </generatorConfiguration>
3、编译生成代码
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; public class GeneratorSqlmap { public void generator() throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; //指定 逆向工程配置文件 File configFile = new File("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) throws Exception { try { GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap(); generatorSqlmap.generator(); } catch (Exception e) { e.printStackTrace(); } } }
4、导入用工具生成pojo,mapper.xml,接口文件,编写测试代码。
//测试 @Test public void TestGetStudent() throws IOException { try { StudentMapper mapper=session.getMapper(StudentMapper.class); System.out.println(mapper); Student student=mapper.selectByPrimaryKey(3); System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); } finally { session.close(); } } //测试 (复杂条件测试) @Test public void TestGetStudent1() throws IOException { try { StudentMapper mapper=session.getMapper(StudentMapper.class); System.out.println(mapper); //1.查询所有: /* StudentExample example=null; List<Student> students=mapper.selectByExample(example); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); */ //2.单个条件查询: /* StudentExample example=new StudentExample(); Criteria criteria= example.createCriteria(); criteria.andTAgeGreaterThan(60); List<Student> students=mapper.selectByExample(example); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); */ //3.多条件查询and: /* StudentExample example=new StudentExample(); Criteria criteria= example.createCriteria(); criteria.andTAgeGreaterThan(20); criteria.andTNameLike("%g%"); List<Student> students=mapper.selectByExample(example); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); */ //4.多条件查询or: /* StudentExample example=new StudentExample(); Criteria criteria= example.createCriteria(); criteria.andTAgeGreaterThan(20); criteria.andTNameLike("%g%"); Criteria criteria1= example.createCriteria(); criteria1.andTSidLessThanOrEqualTo(1); example.or(criteria1); List<Student> students=mapper.selectByExample(example); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); */ //5.排序: /* StudentExample example=new StudentExample(); Criteria criteria= example.createCriteria(); criteria.andTAgeGreaterThan(20); criteria.andTNameLike("%g%"); Criteria criteria1= example.createCriteria(); criteria1.andTSidLessThanOrEqualTo(1); example.or(criteria1); //example.setOrderByClause("t_id desc"); example.setOrderByClause("t_age desc,t_id asc"); List<Student> students=mapper.selectByExample(example); for(Student student :students) System.out.println(student.gettId() + " " + student.gettName() + " "+student.gettAge()+" "+student.gettEnterdate()+" "+student.gettSid()); */ //6.统计 StudentExample example=new StudentExample(); Criteria criteria= example.createCriteria(); //criteria.andTAgeGreaterThan(60); criteria.andTAgeGreaterThan(60); criteria.andTNameLike("%g%"); int count=mapper.countByExample(example); System.out.println(count); } finally { session.close(); } }