天天看點

mybatis generator自動建立代碼及相關問題

1、建立一個檔案夾,其中包括以下檔案和檔案夾:

mysql-connector-java-6.0.3.jar

mybatis-generator-core-1.3.5.jar

mybatis-3.4.1.jar

generateConfig.xml

src

說明:以上.jar包可通過maven工程下載下傳,generatorConfiguration.xml需自己建立。src是建立的一個空檔案夾,用于存放生成的檔案。

2、配置generateConfiguration.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>    
    <!DOCTYPE generatorConfiguration    
      PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"    
      "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">    
    <generatorConfiguration>    
    <!-- 資料庫驅動-->    
        <classPathEntry  location="mysql-connector-java-6.0.3.jar"/>   <!--修改為你的mysql connector的版本--> 
        <context id="DB2Tables"  targetRuntime="MyBatis3">    
            <commentGenerator>    
                <property name="suppressDate" value="true"/>    
                <!-- 是否去除自動生成的注釋 true:是 : false:否 -->    
                <property name="suppressAllComments" value="true"/>    
            </commentGenerator>    
            <!--資料庫連結URL,使用者名、密碼 -->    
            <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" userId="root" password="123456">    
            </jdbcConnection>    
            <javaTypeResolver>    
                <property name="forceBigDecimals" value="false"/>    
            </javaTypeResolver>    
            <!-- 生成模型的包名和位置-->    
            <javaModelGenerator targetPackage="test.domain" targetProject="src">    
                <property name="enableSubPackages" value="true"/>    
                <property name="trimStrings" value="true"/>    
            </javaModelGenerator>    
            <!-- 生成映射檔案的包名和位置-->    
            <sqlMapGenerator targetPackage="test.mapping" targetProject="src">    
                <property name="enableSubPackages" value="true"/>    
            </sqlMapGenerator>    
            <!-- 生成DAO的包名和位置-->    
            <javaClientGenerator type="XMLMAPPER" targetPackage="test.IDao" targetProject="src">    
                <property name="enableSubPackages" value="true"/>    
            </javaClientGenerator>    
            <!-- 要生成的表 tableName是資料庫中的表名或視圖名 domainObjectName是實體類名-->    
            <table tableName="hx_test" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>  
        </context>    
    </generatorConfiguration>    
           

說明:

1)在設定資料庫連接配接<jdbcConnection>時,如果使用的是最新的mysq connectorsl版本(我的為6.0.3),driverClass需設定為“com.mysql.cj.jdbc.Driver”,而不是之前的“com.mysql.jdbc.Driver”。否則将報錯:

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)如果使用的是最新的mysql connectors版本(我的為6.0.3),還需要設定mysql的時區,以使tomcat(server)和mysql的時區同步。如在<jdbcConnection>中設定為connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"。如果不指定serverTimezone=UTC,将報錯:

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 property) 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)在編寫該xml檔案時,注意将第一行“<?xml version="1.0" encoding="UTF-8"?>”頂頭編寫。否則會報以下錯誤:

XML Parser Error on line 1: 不允許有比對 "[xX][mM][lL]" 的處理指令目标。

3、在指令行中,進入上述根檔案夾下,執行指令:java -jar mybatis-generator-core-1.3.5.jar -configfile generateConfig.xml -overwrite,将提示生成檔案。

D:\建立檔案夾>java -jar mybatis-generator-core-1.3.5.jar -configfile generateConfig.xml -overwrite

Cannot obtain primary key information from the database, generated objects may be incomplete

MyBatis Generator finished successfully, there were warnings.

如上設定:執行後提示警告“無法擷取主鍵”,這将導緻生成的接口UserMapper中隻有兩個方法: int insert(User record)、int insertSelective(User record)。而缺少了如下幾個方法:

int deleteByPrimaryKey(Integer id);

User selectByPrimaryKey(Integer id);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);

在網上找了查了好久,也沒有找到解決方法,然後就嘗試使用低版本的mysql-connector(mysql-connector-java-5.1.26-bin.jar)(将配置檔案中的driverClass也修改為com.mysql.cj.jdbc.Driver),就不會再提示警告!

總結:搭環境是還是使用低版本的jar吧,使用最新版的往往都會出現這樣那樣的問題!以後再也不敢嘗試了,心累啊!

執行後生成三個檔案:

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="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="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="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user_t
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="test.domain.User">
    insert into user_t (id, user_name, password, 
      age)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,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,
      </if>
      <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">
        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>
           

繼續閱讀