MyBatis Generator automatically create code and related issues

Source: Internet
Author: User
Tags generator processing instruction table name trim xml parser

1. Create a new folder that includes the following files and folders:

Mysql-connector-java-6.0.3.jar

Mybatis-generator-core-1.3.5.jar

Mybatis-3.4.1.jar

Generateconfig.xml

Src

Description: above. The jar package can be downloaded via MAVEN project and Generatorconfiguration.xml need to be created by yourself. SRC is a newly created empty folder that holds the generated files.

2, the configuration Generateconfiguration.xml, the contents are as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis Generator Configuration 1.0//en" "H Ttp://mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <!--database Driver--  
        > <classpathentry location= "Mysql-connector-java-6.0.3.jar"/> <!--modified to your MySQL connector version---    
                <context id= "Db2tables" targetruntime= "MyBatis3" > <commentGenerator>    
                <property name= "Suppressdate" value= "true"/> <!--whether to remove auto-generated comments true: Yes: false: no--    
            <property name= "Suppressallcomments" value= "true"/> </commentGenerator> <!--database link URL, user name, password--<jdbcconnection driverclass= "Com.mysql.cj.jdbc.Driver" Conne Ctionurl= "Jdbc:mysql://localhost:3306/test?servertimezone=utc" userid= "root" password= "123456 "> </jdbcConnection> <javaTypeResolver> <proper Ty name= "Forcebigdecimals" value= "false"/> </javaTypeResolver> <!--generate the package name and location of the model --<javamodelgenerator targetpackage= "test.domain" targetproject= "src" > <    
            Property Name= "Enablesubpackages" value= "true"/> <property name= "trimstrings" value= "true"/>  </javaModelGenerator> <!--generate a map file package name and location-<sqlmapgenerator Targetpackage= "test.mapping" targetproject= "src" > <property name= "enablesubpackages" Value= "Tru E "/> </sqlMapGenerator> <!--generate DAO's package name and location--&LT;JAVACLIENTG Enerator type= "Xmlmapper" targetpackage= "test. Idao "targetproject=" src "> <property name=" enablesubpackages "value=" true "/> </javaClientGenerator> <!--the table TableName to be generated is the table name or view name in the database domainobjectname is the entity Class name--<table tablename= "hx_test" domainobjectname= "User" enablecountbyexample= "false" Enableupdateby Example= "false" enabledeletebyexample= "false" enableselectbyexample= "false" Selectbyexamplequeryid= "false" >     </table> </context> </generatorConfiguration>
Description

1) When setting up the database connection <jdbcConnection>, if you are using the latest MYSQ CONNECTORSL version (my 6.0.3), Driverclass need to be set to " Com.mysql.cj.jdbc.Driver ", not the previous" Com.mysql.jdbc.Driver ". Otherwise the error will be:

Loading class ' Com.mysql.jdbc.Driver '. This is deprecated. The new driver class is ' com.mysql.cj.jdbc.Driver '. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

2) If you are using the latest MySQL connectors version (my 6.0.3), you also need to set the MySQL time zone to synchronize the time zone of Tomcat (server) and MySQL. As in <jdbcConnection> set to Connectionurl= "JDBC:MYSQL://LOCALHOST:3306/TEST?SERVERTIMEZONE=UTC". If you do not specify SERVERTIMEZONE=UTC, you will be given an error:

Java.sql.SQLException:The Server time zone value '? й??????? ' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the Servertimezone configuration) to use a more specifc Time zone value if you want to utilize time zone support.
At Com.mysql.cj.jdbc.exceptions.SQLError.createSQLException (sqlerror.java:695)
At Com.mysql.cj.jdbc.exceptions.SQLError.createSQLException (sqlerror.java:663)

3) When writing the XML file, be careful to write the first line "<?xml version=" 1.0 "encoding=" UTF-8 "?>" head. Otherwise, the following error is reported:

XML Parser Error on line 1: A processing instruction target that matches "[Xx][mm][ll]" is not allowed.

3, in the command line, enter the above root folder, execute the command: Java-jar mybatis-generator-core-1.3.5.jar-configfile generateconfig.xml-overwrite, The prompt generates a file.

D:\ new Folder >java-jar Mybatis-generator-core-1.3.5.jar-configfile Generateconfig.xml-overwrite
Cannot obtain primary key information from the database, generated objects could be incomplete

MyBatis Generator finished successfully, there were warnings.


As set above: Prompt warning "Unable to get primary key" after execution, which will result in only two methods in the generated interface usermapper: int insert (user record), int insertselective (user record). And the following methods are missing:

int Deletebyprimarykey (Integer ID);

User Selectbyprimarykey (Integer ID);
int updatebyprimarykeyselective (User record);
int Updatebyprimarykey (User record);

Search on the internet for a long time, there is no way to find a solution, You then try to use the lower version of Mysql-connector (Mysql-connector-java-5.1.26-bin.jar) (the Driverclass in the configuration file is also modified to com.mysql.cj.jdbc.Driver), and you are no longer prompted for a warning.


Summary: The use of the environment is still using the lower version of the jar, using the latest version of the often will appear such a problem. Never dare to try again, heart tired ah.


Generate three files after execution:

Usermapper.java:

Package test. Idao;

Import Test.domain.User;

Public interface Usermapper {
    int deletebyprimarykey (Integer ID);

    int Insert (User record);

    int insertselective (User record);

    User Selectbyprimarykey (Integer ID);

    int updatebyprimarykeyselective (User record);

    int Updatebyprimarykey (User record);
}

User.java:

Package test.domain;

public class User {
    private Integer ID;

    Private String userName;

    private String password;

    Private Integer age;

    Public Integer getId () {
        return ID;
    }

    public void SetId (Integer id) {
        this.id = ID;
    }

    Public String GetUserName () {
        return userName;
    }

    public void Setusername (String userName) {
        This.username = UserName = = null? Null:userName.trim ();
    }

    Public String GetPassword () {
        return password;
    }

    public void SetPassword (String password) {
        This.password = password = = null? Null:password.trim ();
    }

    Public Integer Getage () {
        return age;
    }

    public void Setage (Integer age) {
        this.age = age;
    }
}

Usermapper.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < Mapper namespace= "test. Idao.usermapper "> <resultmap id=" baseresultmap "type=" Test.domain.User "> <id column=" id "jdbctype=" integ ER "property=" id "/> <result column=" user_name "jdbctype=" VARCHAR "property=" UserName "/> <result Colu mn= "Password" jdbctype= "VARCHAR" property= "password"/> <result column= "age" jdbctype= "INTEGER" property= "age"/  > </resultMap> <sql id= "base_column_list" > ID, user_name, password, age </sql> <select Id= "Selectbyprimarykey" parametertype= "Java.lang.Integer" resultmap= "Baseresultmap" > select <include refid = "Base_column_list"/> from user_t where id = #{id,jdbctype=integer} </select> <delete id= "Deleteb Yprimarykey "parametertype=" Java.lang.Integer "> Delete from user_t wherE id = #{id,jdbctype=integer} </delete> <insert id= "Insert" parametertype= "Test.domain.User" > Insert I Nto user_t (ID, user_name, password, age) VALUES (#{id,jdbctype=integer}, #{username,jdbctype=varchar}, #{passw Ord,jdbctype=varchar}, #{age,jdbctype=integer}) </insert> <insert id= "insertselective" parametertype= " Test.domain.User "> INSERT INTO user_t <trim prefix=" ("suffix=") "suffixoverrides=", "> <if test= "ID! = NULL" > ID, </if> <if test= "UserName! = null" > User_name, &LT;/IF&G
      T
      <if test= "Password! = null" > Password, </if> <if test= "Age! = null" > Age, </if> </trim> <trim prefix= "VALUES (" suffix= ")" suffixoverrides= "," > <if test= "id ! = null "> #{id,jdbctype=integer}, </if> <if test=" UserName! = null "> #{username , Jdbctype=varchAR}, </if> <if test= "Password! = null" > #{password,jdbctype=varchar}, </if>
  <if test= "Age! = null" > #{age,jdbctype=integer}, </if> </trim> </insert>
      <update id= "updatebyprimarykeyselective" parametertype= "Test.domain.User" > Update user_t <set> <if test= "UserName! = null" > user_name = #{username,jdbctype=varchar}, </if> <if test= " Password! = NULL "> Password = #{password,jdbctype=varchar}, </if> <if test=" Age! = NULL "&G
        T
  Age = #{age,jdbctype=integer}, </if> </set> where id = #{id,jdbctype=integer} </update> <update id= "Updatebyprimarykey" parametertype= "Test.domain.User" > Update user_t set user_name = #{username , Jdbctype=varchar}, Password = #{password,jdbctype=varchar}, age = #{age,jdbctype=integer} where id = #{id , Jdbctype=intEGER} </update> </mapper> 






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.