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(); } }
