Database reverse framework code generation tool: used by MyBatis Generator and mybatisgenerator

Source: Internet
Author: User

Database reverse framework code generation tool: used by MyBatis Generator and mybatisgenerator

The IDEA reverse MyBatis project does not support built-in plug-ins like Hibernate, so you need to integrate a third-party MyBatis Generator.

Detailed introduction to http://mybatis.github.io/generator/index.html for MyBatis Generator

This blog illustrates the use of MyBatis Generator and illustrates the use of reverse engineering based on actual practices.

1. Build the MyBatis Generator plug-in Environment

A. Add the plug-in dependency pom. xml

<! -- Mybatis reverse generation plug-in --> <plugin> <groupId> org. mybatis. generator </groupId> <artifactId> mybatis-generator-maven-plugin </artifactId> <version> 1.3.2 </version> <configuration> <configurationFile> src/main/resources/generatorConfig. xml </configurationFile> <verbose> true </verbose> <overwrite> true </overwrite> </configuration> <executions> <execution> <id> Generate MyBatis Artifacts </id> </execution> </executions> <dependencies> <dependency> <groupId> org. mybatis. generator </groupId> <artifactId> mybatis-generator-core </artifactId> <version> 1.3.2 </version> </dependency> </dependencies> </plugin>

B. configuration file generatorConfig. 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> <properties resource =" jdbc. properties "/> <classPathEntry location =" $ {jdbc_driverLocation} "/> <! -- Specify the location of the jdbc driver jar package for a specific database --> <context id = "default" targetRuntime = "MyBatis3"> <! -- Optional, designed to create a class, control comments --> <commentGenerator> <property name = "suppressDate" value = "true"/> <property name = "suppressAllComments" value = "true"/> </commentGenerator> <! -- Jdbc database connection --> <jdbcConnection driverClass = "$ {jdbc_driverClass}" connectionURL = "$ {jdbc_url}" userId = "$ {jdbc_user}" password = "$ {jdbc_pwd} "> </jdbcConnection> <! -- Not required, type processor, control the conversion between the database type and the java type --> <javaTypeResolver> <property name = "forceBigDecimals" value = "false"/> </javaTypeResolver> <! -- Model generator, used to generate a class containing the primary key, record class and query Example Class targetPackage specify the package name where the generated model is generated targetProject specify the path under this project --> <javaModelGenerator targetPackage = "com. rambo. sdm. dao. pojo "targetProject =" src/main/java "> <! -- Whether to allow sub-packages, that is, targetPackage. schemaName. tableName --> <property name = "enableSubPackages" value = "false"/> <! -- Add constructor to model --> <property name = "constructorBased" value = "true"/> <! -- Whether to trim the data of columns of the CHAR type --> <property name = "trimStrings" value = "true"/> <! -- Whether the created Model object cannot be changed. That is, the generated Model object does not have the setter method, only the constructor --> <property name = "immutable" value = "false"/> </javaModelGenerator> <! -- The directory where the Mapper ing file is generated generates the corresponding SqlMap file for each database table --> <sqlMapGenerator targetPackage = "com. rambo. sdm. dao. mapper "targetProject =" src/main/java "> <property name =" enableSubPackages "value =" false "/> </sqlMapGenerator> <! -- Client code: Generate easy-to-use code type = "ANNOTATEDMAPPER" for Model objects and XML configuration files, and generate Java Model and annotation-based Mapper object type = "MIXEDMAPPER ", generate annotation-based Java Model and corresponding Mapper object type = "XMLMAPPER", generate SQLMap XML file and independent Mapper interface --> <javaClientGenerator targetPackage = "com. rambo. sdm. dao. inter "targetProject =" src/main/java "type =" XMLMAPPER "> <property name =" enableSubPackages "value =" true "/> </javaClientGenerator> <table tableName =" user "domainObjectName =" UserPO "> <generatedKey column =" uuid "sqlStatement =" select replace (UUID (), '-', '') uuid from dual"/> </table> </context> </generatorConfiguration>

C. Database Configuration File jdbc. properties

jdbc_driverLocation=D:\\Program Files\\Repository\\mysql\\mysql-connector-java\\5.1.38\\mysql-connector-java-5.1.38.jarjdbc_driverClass=com.mysql.jdbc.Driverjdbc_url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&amp;characterEncoding=utf-8jdbc_user=rootjdbc_pwd=123456validationQuery = select 1

D. Configure the plug-in startup Item

2. Project Practice

The User class is a common entity class that defines the fields corresponding to the database and the set/get method.

Mybatis introduces the Example class to encapsulate database query conditions.

A. For example, in a project, we want to delete the information of a user in a group.

    public int deleteUserApplyInfo(long user_id,long team_id){        StudyTeamUserApplyInfoExample ue = new StudyTeamUserApplyInfoExample();        ue.createCriteria().andUserIdEqualTo(new BigDecimal(user_id)).andTeamIdEqualTo(new BigDecimal(team_id));        return studyTeamUserApplyInfoDAO.deleteByExample(ue);    }

2. Update group information based on group ID (non-primary key)

   public int updateStudyTeamInfo(StudyTeamInfo st){        StudyTeamInfoExample ste = new StudyTeamInfoExample();        ste.createCriteria().andTeamIdEqualTo(st.getTeamId());        return studyTeamInfoDAO.updateByExampleSelective(st,ste);    }

3. (1) fuzzy query and sorting (2) query with a score greater than or equal to a score smaller than a certain score

public List<StudyTeamInfo> getStudyTeamInfoByName(String team_name){        StudyTeamInfoExample se = new StudyTeamInfoExample();        se.createCriteria().andTeamNameLike("%"+team_name+"%").andEnableEqualTo((short)1);        se.setOrderByClause("team_score desc");        List<StudyTeamInfo> ls = studyTeamInfoDAO.selectByExample(se);        if(ls!=null&&ls.size()>0){            return ls;        }        return null;    }

 

public StudyTeamLevel getStudyTeamLevel(long score){        StudyTeamLevelExample le = new StudyTeamLevelExample();        le.createCriteria().andNeedScoreLessThanOrEqualTo(score).andUpScoreGreaterThan(score);        List<StudyTeamLevel> ls = studyTeamLevelDAO.selectByExample(le);        if(ls!=null&&ls.size()>0){            return ls.get(0);        }        return null;    }

 

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.