Mybatis (8) reverse engineering and mybatis Reverse Engineering

Source: Internet
Author: User

Mybatis (8) reverse engineering and mybatis Reverse Engineering

Mybaits requires programmers to write their own SQL statements. mybatis provides reverse engineering, which can automatically generate the code (mapper. java, mapper. xml, pojo, etc.) with the SQL table structure, we can use reverse engineering to directly generate the corresponding Dao and JavaBean code, and mapper. xml file, which can greatly reduce the workload we usually develop. However, due to the limitations of reverse engineering, the reverse engineering method can only be executed once. If it is executed again, the corresponding Dao and JavaBean will continue to be generated unless we delete all the previously generated ones. In this way, the Code scalability is not very good. If we need to modify the table structure, we must modify the generated Dao and JavaBean one by one, or re-generate a new copy.

MyBatis Generator: MBG for short. It is a code Generator specially designed for MyBatis framework users. It can quickly generate corresponding ing files, interfaces, and bean classes based on tables. Supports basic addition, deletion, modification, and query of QBC-style conditions. However, the definition of complex SQL statements such as table join and stored procedure needs to be compiled manually.

Document reference:

Http://www.mybatis.org/generator/

Download from the official website:

Https://github.com/mybatis/

The download procedure is as follows:

      

 

 

        

        

Procedure:

1. Import related jar packages: mysql and CMDL are supported here.

    

 

2. Compile the MBG configuration file (important)

1) Configure database connection information in jdbcConnection

2) configure the javaBean generation policy for javaModelGenerator

3) sqlMapGenerator: configure the SQL ing file generation policy

4) configure the Mapper Interface Generation Policy for javaClientGenerator

5) configure the data table to be reverse parsed in table (tableName: table Name, domainObjectName: Corresponding javaBean name)

Run the code generator to generate the code. Note the Context label. targetRuntime = "MyBatis3" can generate addition, deletion, modification, and query with conditions. targetRuntime = "MyBatis3Simple" can generate basic addition, deletion, modification, and query. If yes, we recommend that you delete the previously generated data to avoid the problem of adding content to the backend of xml.

 

  

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE generatorConfiguration PUBLIC "-// mybatis.org//DTD MyBatis Generator Configuration 1.0 //" http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <context id =" testTables "targetRuntime =" MyBatis3 "> <commentGenerator> <! -- Whether to remove automatically generated comments true: Yes: false: No --> <property name = "suppressAllComments" value = "true"/> </commentGenerator> <! -- Database connection information: Driver Class, connection address, user name, password --> <jdbcConnection driverClass = "com. mysql. jdbc. driver "connectionURL =" jdbc: mysql: // 192.168.61.22: 3306/test "userId =" root "password =" 123456 "> </jdbcConnection> <! -- The default value is false. The jdbc decimal and NUMERIC types are parsed to Integer. If the value is true, the jdbc decimal and NUMERIC types are parsed to java. math. bigDecimal --> <javaTypeResolver> <property name = "forceBigDecimals" value = "false"/> </javaTypeResolver> <! -- TargetProject: location where the PO class is generated --> <javaModelGenerator targetPackage = "com. softjx. model" targetProject = ". \ src"> <! -- EnableSubPackages: whether to use schema as the package suffix --> <property name = "enableSubPackages" value = "false"/> <! -- Space before and after the value returned from the database --> <property name = "trimStrings" value = "true"/> </javaModelGenerator> <! -- TargetProject: er ing file generation location --> <sqlMapGenerator targetPackage = "com. softjx. dao" targetProject = ". \ src"> <! -- EnableSubPackages: whether to use schema as the package suffix --> <property name = "enableSubPackages" value = "false"/> </sqlMapGenerator> <! -- TargetPackage: Location generated by the ER interface --> <javaClientGenerator type = "XMLMAPPER" targetPackage = "com. softjx. dao" targetProject = ". \ src"> <! -- EnableSubPackages: whether to use schema as the package suffix --> <property name = "enableSubPackages" value = "false"/> </javaClientGenerator> <! -- Specify a database table --> <table schema = "test" tableName = "school" domainObjectName = "School"> </table> <table schema = "test" tableName = "student" domainObjectName = "Student"> </table> </context> </generatorConfiguration>

3. compile and generate code

  

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; // specify the reverse engineering configuration 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. import and use tools to generate pojo, mapper. xml, interface files, and write test code.

 

// Test @ 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 (complex condition Test) @ Test public void TestGetStudent1 () throws IOException {try {StudentMapper mapper = session. getMapper (StudentMapper. class); System. out. println (mapper); // 1. query all:/* 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. single condition query:/* 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. multi-condition query 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. multi-condition query or:/* StudentExample example = new StudentExample (); Criteria criteria = example. createCriteria (); criteria. andTAgeGreaterThan (20); criteria. andTNameLike ("% g %"); Criteria criteria1 = example. createCriteria (); criteria1.andtsidlessthanorto to (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. sort:/* StudentExample example = new StudentExample (); Criteria criteria = example. createCriteria (); criteria. andTAgeGreaterThan (20); criteria. andTNameLike ("% g %"); Criteria criteria1 = example. createCriteria (); criteria1.andtsidlessthanorto to (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. count 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 ();}}

 

Related Article

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.