MyBatis framework of MyBatis reverse engineering automatic generation of code _java

Source: Internet
Author: User
Tags generator manual writing

MyBatis is a semi-automatic ORM, in the use of this framework, the biggest workload is to write mapping mapping file, because manual writing is very error-prone, we can use Mybatis-generator to help us automatically generate files.

Reverse engineering

1. What is reverse engineering

Mybaits need programmers to write their own SQL statements, mybatis the official provision of reverse engineering can automatically generate MyBatis execution for a single table code (mapper.java,mapper.xml, Po ... )

In the actual development of enterprises, the commonly used reverse engineering methods:
Because the database's tables generate Java code.

2. Download Reverse Engineering

Mybatis-generator-core-1.3.2-bundle.zip

3. Use method (will be used)

3.1 Running Reverse engineering

Several methods of running reverse engineering provided in official documents

Running MyBatis Generator

MyBatis Generator (MBG) can is run in the following ways:

(1) From the command prompt and an XML configuration

(2) As Ant task with an XML configuration

(3) As a Maven Plugin

(4) From another Java programming with an XML configuration

(5) From another Java programming with a Java based configuration

(6) can also generate code through Eclipse's Plug-ins

It is recommended that you use Java program methods (from another Java programs with an XML configuration) without relying on development tools.

The following creates a project to generate a reverse file, and then copies the automatically generated files to the original project (in order to stop the build in the source file that will overwrite the file with the same name) import the jar package and the engineering structure screenshot as follows:

As shown in figure


3.2 Generate code configuration file

Generatorconfig.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis generator Configuration" "1.0//en Mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <context id=" Testtables " Targetruntime= "MyBatis3" > <commentGenerator> <!--whether to remove automatically generated comments true: false: No--> <property name= " Suppressallcomments "value=" true "/> </commentGenerator> <!--database connection information: Driver class, connection address, username, password--> < Jdbcconnection driverclass= "Com.mysql.jdbc.Driver" connectionurl= "Jdbc:mysql://localhost:3306/mybatis"
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 to resolve JDBC decimal and NUMERIC types to Integer, and to resolve JDBC decimal and NUMERIC types to Java.math.BigDecimal when True
; <javaTypeResolver> <propertY name= "Forcebigdecimals" value= "false"/> </javaTypeResolver> <!--targetproject: Generate PO class location--> < Javamodelgenerator targetpackage= "Cn.edu.hpu.ssm.po" targetproject= "\src" > <!--enablesubpackages: Whether to have schema as the suffix of the package--> <property name= "Enablesubpackages" value= "false"/> <!--the space before and after the value returned from the database is cleaned--> < Property Name= "Trimstrings" value= "true"/> </javaModelGenerator> <!--targetproject:mapper Map file generation location- > <sqlmapgenerator targetpackage= "cn.edu.hpu.ssm.mapper" targetproject= "\src" > <!--enablesubpackages: Whether to have schema as the suffix of the package--> <property name= "Enablesubpackages" value= "false"/> </sqlMapGenerator> <!-- 
Targetpackage:mapper interface generated location--> <javaclientgenerator type= "Xmlmapper" targetpackage= "Cn.edu.hpu.ssm.mapper" Targetproject= ". \src" > <!--enablesubpackages: whether to have 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 need to specify the Java type <table schema=" Tablename= "" > < Columnoverride column= "" javatype= ""/> </table>--> </context> </generatorConfiguration>

3.3 Executing the Build 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<st
Ring> ();
Boolean overwrite = true; 
Load profile 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 (); }
}
}

Post-generated code:


3.4 Using the generated code

The code generated in the build project needs to be copied into its own project. Here we go. Itemsmapper.java and Itemsmapper.xml, Items, Itemsexample class into our original project.

Testing the 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; Note Before call this method before executing all of the test methods in this class @Before public void Setup () throws exception{Applicationcontext=new
Classpathxmlapplicationcontext ("Classpath:spring/applicationcontext.xml");
Itemsmapper= (Itemsmapper) Applicationcontext.getbean ("Itemsmapper");  ///delete @Test public void Testdeletebyprimarykey () {fail ("not yet implemented") by primary key;}//Insert @Test public void Testinsert () {Items items=new items (); Items.setname ("iphone-5s"); Items.setprice (3999f); Items.setdetail ("authentic licensed"); Items.setpic (" SDasd.jpg ");
Items.setcreatetime (New Date ());
Itemsmapper.insert (items); //Custom criteria to query @Test public void Testselectbyexample () {itemsexample itemsexample=new itemsexample ();//construct query criteria by criteria I
Temsexample.criteria Criteria=itemsexample.createcriteria ();
Criteria.andnameequalto ("TV");
More than one record may be returned 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 @Test public void Testselectbyprimarykey () {Items Items=itemsmapper.selectbyprimarykey (1) According to the primary key;
System.out.println (Items.getname ()); }//Update data @Test public void Testupdatebyprimarykey () {//Update all fields, need to query and update the items = Itemsmapper.selectbyprimarykey 
(1); 
Items.setname ("IPhone");
Itemsmapper.updatebyprimarykey (items);
If the incoming field is not empty to update, use this method in batch update, do not need to query before updating//itemsmapper.updatebyprimarykeyselective (record); }
}

The above is a small set to introduce the MyBatis framework of the MyBatis reverse engineering automatically generate code, I hope to help you!

Recommended readings for cloud-dwelling communities:

MyBatis Introductory Learning Course (i)-mybatis QuickStart

An in-depth analysis of MyBatis Oracle BLOB Type field save and read

DAO and Mapper of MyBatis practice

Dynamic SQL and associated query of MyBatis practice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.