Mybatis is a semi-automatic ORM. In using this framework, the most workload is to write Mapping mapping files. Since manual writing is easy to make mistakes, we can use Mybatis-Generator to help us automatically generate files.
Reverse Engineering
1. What is reverse engineering
Mybaits requires programmers to write sql statements themselves. Mybatis official provides reverse engineering to automatically generate the required code for mybatis execution (mapper.java, mapper.xml, po..)
Common reverse engineering methods used in actual enterprise development:
Java code is generated due to the table of the database.
2. Download reverse engineering
mybatis-generator-core-1.3.2-bundle.zip
3. How to use (can use it)
3.1 Run reverse engineering
Several ways to run reverse engineering provided in the official documentation
Running MyBatis Generator
MyBatis Generator (MBG) can be run in the following ways:
(1) From the command prompt with an XML configuration
(2)As an Ant task with an XML configuration
(3)As a Maven Plugin
(4) From another Java program with an XML configuration
(5) From another Java program with a Java based configuration
(6) You can also generate code through the eclipse plug-in
It is recommended to use the Java program method (From another Java program with an XML configuration) and do not rely on development tools.
Below is a project that generates reverse files, and then copy the automatically generated files to the original project (this is done to stop directly generating in the source file and overwrite the file with the same name). The screenshot of the imported jar package and project structure is as follows:
As shown
3.2 Generate code configuration files
generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//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><!-- Whether to remove the auto-generated comments true: Yes: false: No--><property name="suppressAllComments" value="true" /></commentGenerator><!--Information of database connection: driver class, connection address, username, password--><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"password="1234"></jdbcConnection><!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg"password="yycg"></jdbcConnection> --><!-- Default false, parse the JDBC DECIMAL and NUMERIC types to Integer, and when true, parse the JDBC DECIMAL and NUMERIC types to java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject: The location where the PO class is generated --><javaModelGenerator targetPackage="cn.edu.hpu.ssm.po"targetProject="./src"><!-- enableSubPackages: Whether to let schema be the suffix of the package --><property name="enableSubPackages" value="false" /><!-- value returned from the database is cleaned --><property name="trimStrings" value="true" /></javaModelGenerator><!-- targetProject: The location where the mapper map file is generated --><sqlMapGenerator targetPackage="cn.edu.hpu.ssm.mapper" targetProject="./src"><!-- enableSubPackages: Whether to use schema as the suffix of the package --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage: Location of mapper interface generation --><javaClientGenerator type="XMLMAPPER" targetPackage="cn.edu.hpu.ssm.mapper" targetProject="./src"><!-- enableSubPackages: Whether to use schema as the suffix of the package --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- Specify database table--><table tableName="items"></table><table tableName="orders"></table><table tableName="orderdetail"></table><table tableName="user"></table><!-- <table schema="" tableName="sys_user"></table><table schema="" tableName="sys_role"></table><table schema="" tableName="sys_permission"></table><table schema="" tableName="sys_user_role"></table><table schema="" tableName="sys_role_permission"></table> --><!-- Some table fields require java type<table schema="" tableName=""><columnOverride column="" javaType="" /></table> --></context></generatorConfiguration>
3.3 Execute the generator program
GeneratorSqlmap.java:
import java.io.File;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.internal.DefaultShellCallback;public class GeneratorSqlmap {public void generator() throws Exception{List<String> warnings = new ArrayList<String>();boolean overwrite = true;//Load configuration file 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();}}}Generated code:
3.4 Using generated code
You need to copy the generated code in the generated project to your own project. Let's copy the ItemsMapper.java and ItemsMapper.xml, Items, and ItemsExample classes into our original project.
Testing methods in ItemsMapper
package cn.edu.hpu.ssm.test;import static org.junit.Assert.fail;import java.util.Date;import java.util.List;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.edu.hpu.ssm.mapper.ItemsMapper;import cn.edu.hpu.ssm.po.Items;import cn.edu.hpu.ssm.po.ItemsExample;public class ItemsMapperTest {private ApplicationContext applicationContext;private ItemsMapper itemsMapper;//Annotation Before calling this method before executing all test methods of this class @Beforepublic void setup() throws Exception{applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");itemsMapper=(ItemsMapper)applicationContext.getBean("itemsMapper");}//Delete @Testpublic void testDeleteByPrimaryKey() {fail("Not yet implemented");}//Insert @Testpublic void testInsert() {Items items=new Items();items.setName("iPhone-5S");items.setPrice(3999f);items.setDetail("authentic");items.setPic("sdasd.jpg");items.setCreatetime(new Date());itemsMapper.insert(items);}//Customize the conditions to query @Testpublic void testSelectByExample() {ItemsExample itemsExample=new ItemsExample();//Construct the query conditions through Criteria ItemsExample.Criteria criteria=itemsExample.createCriteria();criteria.andNameEqualTo("TV");//May return multiple records List<Items> list=itemsMapper.selectByExample(itemsExample); for (int i = 0; i < list.size(); i++) {Items it=list.get(i); System.out.println(it.getId()+":"+it.getName());}}//Query based on the primary key @Testpublic void testSelectByPrimaryKey() {Items items=itemsMapper.selectByPrimaryKey(1);System.out.println(items.getName());}//Update data @Testpublic void testUpdateByPrimaryKey() {//Update all fields, you need to query first and then update Items items = itemsMapper.selectByPrimaryKey(1); items.setName("iPhone"); itemsMapper.updateByPrimaryKey(items);//If the incoming field is not empty, use this method in batch updates. There is no need to query first and then update //itemsMapper.updateByPrimaryKeySelective(record);}}The above is the MyBatis reverse engineering automatic code generated by the MyBatis framework introduced to you by the editor. I hope it will be helpful to everyone!
Recommended readings from Wulin.com:
MyBatis Introduction Learning Tutorial (I) - MyBatis Quick Start
In-depth analysis of mybatis oracle BLOB type fields saving and reading
MyBatis Practice DAO and Mapper
Dynamic SQL and associated query in MyBatis practice