MyBatis Generator (MBG) 是一個Mybatis的代碼生成器,它可以幫助我們根據數據庫中表的設計生成對應的實體類,xml Mapper文件,接口以及幫助類(也就是我們可以藉助該類來進行簡單的CRUD操作),這樣就避免了我們每使用到一張表的數據就需要手動去創建對應的類和xml文件,這就幫我們節約了大量的時間去開發和業務邏輯有關的功能。
1、通過Eclipse插件的方式使用generator
1.1、將MyBatis Generator\eclipse文件夾拷貝到eclipse安裝路徑下的dropins文件夾下。然後重啓Eclipse
1.2、將generator.xml文件拷貝到項目的src文件夾中
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="context1" targetRuntime="MyBatis3">
<commentGenerator>針對自動註釋的配置信息,也就是說默認反向引擎會自動生成一些註釋信息,可以選擇關閉
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521:ORCL" userId="shake"
password="kesha"></jdbcConnection>數據庫連接相關配置
<javaModelGenerator targetPackage="com.yan.entity實體類的包名稱"
targetProject="yan當前的項目名稱">設置實體類的存放位置
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.yan.mapper映射元文件的包名稱,實際上是目錄名稱"targetProject="yan當前的項目名稱">設置生成的映射元文件的存放位置
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"targetPackage="com.yan.dao映射接口的包名稱" implementationPackage="com.yan.dao.impl" targetProject="yan當前的項目名稱">設置生成的映射接口的存放位置
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<table tableName="t_cx對應的表名稱,針對這個表需要進行反向映射" domainObjectName="FoodCatalogBean設置對應這個表的實體類名稱"></table>
</context>
</generatorConfiguration>
1.3、右鍵點擊generator.xml
執行反向工程時常見的一個報錯信息
因爲generator採用的而是命令行的方式執行,這個報錯信息意思是不能獲取到數據庫驅動[maven和web開發]
解決方法:
如果驅動不在當前項目中還可以使用
第二問題:反應引擎採用的是追加的方式,如果需要多次反向映射,要先刪除就有的定義,然後再進行反向映射
自動生成的內容有
UserBeanMapper.java是映射接口;UserBeanMapper.xml是映射元文件,UserBean.java是實體類,UserBeanExample.java是用於執行復雜查詢的工具類【不建議,太麻煩,可能有類爆炸問題】
使用反向映射時不建議生成xxxExample文件的配置
<table tableName="emp" schema="scott" domainObjectName="EmpBean"></table>會生成對應的Example類,如果不需要生成則添加配置enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"
2.編程實現反向映射[具體應用中使用較多]
2.1添加相關jar包
2,2添加generator.xml文件
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="context1" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mysql" userId="root"
password="root">
</jdbcConnection>
<!--
<jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521:ORCL" userId="scott"
password="tiger">
</jdbcConnection>
-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="com.lq.entity"
targetProject="./src">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.lq.mapper"
targetProject="./src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.lq.dao" implementationPackage="com.lq.dao.impl"
targetProject="./src">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<table tableName="t_users" domainObjectName="UserBean"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
<!--
<table tableName="emp" schema="scott" domainObjectName="EmpBean">
</table>
-->
</context>
</generatorConfiguration>
2.3反向工程java類:generator.java
package com.lq;
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 Generator {
public static void main(String[] args)throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File f = new File("src/generator.xml");
ConfigurationParser parser=new ConfigurationParser(warnings);
Configuration cfg=parser.parseConfiguration(f);
DefaultShellCallback callback=new DefaultShellCallback(overwrite);
MyBatisGenerator generator=new MyBatisGenerator(cfg,callback, warnings);
generator.generate(null);
System.out.println("反向工程執行完畢");
}
}
2.4生成如下圖所示接口,實體類及映射文件
UserBeanMapper.java:
package com.lq.dao;
import com.lq.entity.UserBean;
public interface UserBeanMapper {
int deleteByPrimaryKey(Long id);
int insert(UserBean record);
int insertSelective(UserBean record);
UserBean selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(UserBean record);
int updateByPrimaryKey(UserBean record);
}
UserBean.java:
package com.lq.entity;
import java.math.BigDecimal;
import java.util.Date;
public class UserBean {
private Long id;
private String username;
private String password;
private Date birth;
private Boolean sex;
private BigDecimal salary;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
}
UserBeanMapper.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="com.lq.dao.UserBeanMapper">
<resultMap id="BaseResultMap" type="com.lq.entity.UserBean">
<id column="Id" jdbcType="BIGINT" property="id" />
<result column="Username" jdbcType="VARCHAR" property="username" />
<result column="Password" jdbcType="VARCHAR" property="password" />
<result column="Birth" jdbcType="TIMESTAMP" property="birth" />
<result column="Sex" jdbcType="BIT" property="sex" />
<result column="Salary" jdbcType="DECIMAL" property="salary" />
</resultMap>
<sql id="Base_Column_List">
Id, Username, Password, Birth, Sex, Salary
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_users
where Id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from t_users
where Id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.lq.entity.UserBean">
insert into t_users (Id, Username, Password,
Birth, Sex, Salary)
values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{birth,jdbcType=TIMESTAMP}, #{sex,jdbcType=BIT}, #{salary,jdbcType=DECIMAL})
</insert>
<insert id="insertSelective" parameterType="com.lq.entity.UserBean">
insert into t_users
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
Id,
</if>
<if test="username != null">
Username,
</if>
<if test="password != null">
Password,
</if>
<if test="birth != null">
Birth,
</if>
<if test="sex != null">
Sex,
</if>
<if test="salary != null">
Salary,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="birth != null">
#{birth,jdbcType=TIMESTAMP},
</if>
<if test="sex != null">
#{sex,jdbcType=BIT},
</if>
<if test="salary != null">
#{salary,jdbcType=DECIMAL},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.lq.entity.UserBean">
update t_users
<set>
<if test="username != null">
Username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
Password = #{password,jdbcType=VARCHAR},
</if>
<if test="birth != null">
Birth = #{birth,jdbcType=TIMESTAMP},
</if>
<if test="sex != null">
Sex = #{sex,jdbcType=BIT},
</if>
<if test="salary != null">
Salary = #{salary,jdbcType=DECIMAL},
</if>
</set>
where Id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.lq.entity.UserBean">
update t_users
set Username = #{username,jdbcType=VARCHAR},
Password = #{password,jdbcType=VARCHAR},
Birth = #{birth,jdbcType=TIMESTAMP},
Sex = #{sex,jdbcType=BIT},
Salary = #{salary,jdbcType=DECIMAL}
where Id = #{id,jdbcType=BIGINT}
</update>
</mapper>