在之前的工程中,实现一个查询功能,首先要根据数据库中的相关表创建响应的Java实体类,然后还需要配置一个SQL映射文件,如果使用Mapper动态代理,还需要定义一个与SQL映射文件对应的Dao接口。在大型工程的开发中,有时需要创建很多的Java实体类和SQL映射文件,以及Dao接口,而且很多时候,除了负责的业务SQL外,还需要重复编写每一个表的基本增、删、改、查SQL配置,这会降低开发效率。
对于这个问题,MyBatis官方提供了一种名为“逆向工程”的机制,其可以针对数据库中的单表自动生成MyBatis执行所需要的代码(包括Java实体类、SQL映射文件配置及Dao接口)。使用逆向工程,可以大大减少重复的配置和创建工作,提升开发效率。
要使用MyBatis逆向工程,除了需要MyBatis本身的依赖jar包外,还需要下载MyBatis逆向工程相应的依赖jar包。这里使用版本为1.3.2,名为“mybatis-generator-core-1.3.2.jar”的依赖jar包。将该jar包拷贝到WEB-INF/lib下,并添加为工程依赖(Add as Library)
在mybatis数据库中创建名为“goods”的商品数据表,并在该表中添加测试数据。具体的建表和添加测试数据SQL语句如下:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `goods`
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`id` int(255) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`price` double(255,0) default NULL,
`number` int(255) default NULL,
`type` varchar(255) default NULL,
`no` varchar(255) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES ('1', 'Bose QC35II', '2889', '50', '耳机', 'EJ456138');
INSERT INTO `goods` VALUES ('2', 'SKII 神仙水', '1035', '20', '化妆品', 'MZ789463');
INSERT INTO `goods` VALUES ('3', 'NIKE KD 15', '1689', '30', '鞋类', 'XZ459317');
逆向工程如何做到由数据库生成相关的Java代码及配置文件呢?其实这些数据都编写在逆向工程配置文件generatorConfig.xml中。该配置文件会告诉逆向工程引擎,需要加载哪个数据库、哪些表,生成的Java实体类、SQL映射文件、Dao代理接口的位置,以及某些表中的数据对应的Java类型等。
在src下创建名为com.ccff.mybatis.mapper的包,该包用于存放通过MyBatis逆向数据生成的SQL映射文件。
在config文件夹下创建名为“generatorConfig.xml”的逆向工程配置文件,具体配置如下:
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"
password="root">
jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
javaTypeResolver>
<javaModelGenerator targetPackage="com.ccff.mybatis.model"
targetProject=".\src">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
javaModelGenerator>
<sqlMapGenerator targetPackage="com.ccff.mybatis.mapper"
targetProject=".\src">
<property name="enableSubPackages" value="false" />
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.ccff.mybatis.dao"
targetProject=".\src">
<property name="enableSubPackages" value="false" />
javaClientGenerator>
<table tableName="goods">
<columnOverride column="price" javaType="java.lang.Double" />
<columnOverride column="name" javaType="java.lang.String" />
<columnOverride column="type" javaType="java.lang.String" />
<columnOverride column="no" javaType="java.lang.String" />
table>
context>
generatorConfiguration>
在上面的配置文件中,首先加入MyBatis逆向工程的DTD格式声明,然后为generatorConfiguration标签对,其中放置逆向工程的主要配置。每一个context配置代表每一个单独的逆向配置。在context标签中:
commentGenerator标签: 定义了不生成注释的参数配置。
jdbcConnection标签: 配置了逆向工程需要连接的数据库信息。
javaTypeResolver标签: 主要指定JDBC中的相关类型,是否被强制转换成某种类型(默认false,把JDBC DECIMAL和 NUMERIC类型解析为Integer,为 true时把JDBC DECIMAL和NUMERIC类型解析为java.math.BigDecimal)。
javaModelGenerator标签: 配置了生成Java实体类的位置。
sqlMapGenerator标签: 配置了生成SQL映射文件的位置。
javaClientGenerator标签: 配置了生成Dao代理接口的位置。
table标签: 指定逆向工程操作的表信息,可以配置多个表信息。对于该标签,有些表中的某个字段需要被转换成指定的Java类型,那么可以在该table标签中添加单独对该类型的转换配置。例如在上述配置中对price字段的转换。
编写完配置文件后,需要再创建执行类来加载配置文件,对数据表进行逆向工程的构建。
在src目录下创建名为“com.ccff.mybatis.generator”的包,该包下用于存储逆向工程执行类,在该包下创建名为“GeneratorSqlMap”的执行类,具体代码如下:
package com.ccff.mybatis.generator;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.ShellCallback;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GeneratorSqlMap {
public void generator() throws Exception{
//warnings为用于放置生成过程中警告信息的集合对象
List<String> warnings = new ArrayList<String>();
//指定DefaultShellCallback是否覆盖重名文件
boolean overwrite = true;
//加载配置文件
String path = "./config/generatorConfig.xml";
File configFile = new File(path);
//配置解析类
ConfigurationParser cp = new ConfigurationParser(warnings);
//配置解析类解析配置文件并生成Configuration配置对象
Configuration config = cp.parseConfiguration(configFile);
//DefaultShellCallback负责如何处理重复文件
ShellCallback callback = new DefaultShellCallback(overwrite);
//逆向工程对象
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
//执行逆向文件生成操作
myBatisGenerator.generate(null);
}
public static void main(String[] args) throws Exception {
GeneratorSqlMap generatorSqlmap = new GeneratorSqlMap();
generatorSqlmap.generator();
}
}
在该类中,首先使用FIle类生成generatorConfig.xml配置文件的File对象,然后创建用于解析配置文件的配置解析类ConfigurationParser,使用该类解析File对象,获取具体的配置对象Configuration。
然后创建ShellCallback对象,该对象主要负责把project属性或者package属性翻译成目录结构。还指定在生成文件时,在Java或者XML文件已经存在的情况下,如何处理这些重复的文件。ShellCallback接口的默认实现为org.mybatis.generator.internal.DefaultShellCallback,这个默认实现只负责把project和package直接翻译成文件结构,如果某些文件夹不存在,则创建。另外对于重复的文件,默认实现也只能选择覆盖或者忽略(overwrite参数设置为true,选择覆盖)。
接下来将config配置对象、callback处理对象及warnings警告信息集合对象,作为参数放入MyBatisGenerator的构造方法中,生成具体的逆向工程处理对象myBatisGenerator,然后执行generate方法进行逆向文件的生成。
运行GeneratorSqlMap类中的main方法来执行逆向方法,运行后可以发现工程生成了新的文件,目录发生了改变,具体如下所示:
可以看到,在com.ccff.mybatis.dao包下生成了名为“GoodsMapper”的Dao代理接口。在com.ccff.mybatis.mapper包下生成了名为“GoodsMapper.xml”的SQL映射文件。在com.ccff.mybatis.model包下生成了名为“Goods”的Java实体类和名为“GoodsExample”的查询包装类。
其中Dao代理接口和SQL映射文件中都定义了Goods最基本的增、删、改、查方法,以及其他常用的数据库操作(如数据统计),而Goods包装类即是数据库中goods表的字段的实体映射,GoodsExample是复杂查询或修改操作的条件包装。
在GoodsMapper代理接口中,countByExample方法根据传入的复杂条件封装类GoodsExample查询出结果总数;deleteByExample方法根据传入的复杂条件封装类GoodsExample删除符合条件的列;deleteByPrimaryKey方法根据传入的Integer类型的id删除该id对应的列;insert和insertSelective方法根据传入的Goods封装类在表中插入该商品信息;selectByExample方法根据传入的复杂条件封装类GoodsExample查询出符合条件的多个用户集合数据;selectByPrimaryKey方法根据传入的Integer类型的id查询单个用户信息;updateByExampleSelective和updateByExample方法根据传入的复杂条件封装类GoodsExample对符合条件的信息进行部分或全部修改;updateByPrimaryKeySelective和updateByPrimaryKey方法根据传入的Goods包装对象中的id属性查询符合条件的商品信息,并根据Goods包装类中的其他属性进行全部或部分修改。
生成的Dao接口文件如下:
package com.ccff.mybatis.dao;
import com.ccff.mybatis.model.Goods;
import com.ccff.mybatis.model.GoodsExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface GoodsMapper {
int countByExample(GoodsExample example);
int deleteByExample(GoodsExample example);
int deleteByPrimaryKey(Integer id);
int insert(Goods record);
int insertSelective(Goods record);
List<Goods> selectByExample(GoodsExample example);
Goods selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Goods record, @Param("example") GoodsExample example);
int updateByExample(@Param("record") Goods record, @Param("example") GoodsExample example);
int updateByPrimaryKeySelective(Goods record);
int updateByPrimaryKey(Goods record);
}
生成的SQL映射文件如下:
<mapper namespace="com.ccff.mybatis.dao.GoodsMapper" >
<resultMap id="BaseResultMap" type="com.ccff.mybatis.model.Goods" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="price" property="price" jdbcType="DOUBLE" />
<result column="number" property="number" jdbcType="INTEGER" />
<result column="type" property="type" jdbcType="VARCHAR" />
<result column="no" property="no" jdbcType="VARCHAR" />
resultMap>
<sql id="Example_Where_Clause" >
<where >
<foreach collection="oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
foreach>
when>
choose>
foreach>
trim>
if>
foreach>
where>
sql>
<sql id="Update_By_Example_Where_Clause" >
<where >
<foreach collection="example.oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
foreach>
when>
choose>
foreach>
trim>
if>
foreach>
where>
sql>
<sql id="Base_Column_List" >
id, name, price, number, type, no
sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.ccff.mybatis.model.GoodsExample" >
select
<if test="distinct" >
distinct
if>
<include refid="Base_Column_List" />
from goods
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
if>
<if test="orderByClause != null" >
order by ${orderByClause}
if>
select>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from goods
where id = #{id,jdbcType=INTEGER}
select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from goods
where id = #{id,jdbcType=INTEGER}
delete>
<delete id="deleteByExample" parameterType="com.ccff.mybatis.model.GoodsExample" >
delete from goods
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
if>
delete>
<insert id="insert" parameterType="com.ccff.mybatis.model.Goods" >
insert into goods (id, name, price,
number, type, no)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=DOUBLE},
#{number,jdbcType=INTEGER}, #{type,jdbcType=VARCHAR}, #{no,jdbcType=VARCHAR})
insert>
<insert id="insertSelective" parameterType="com.ccff.mybatis.model.Goods" >
insert into goods
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
if>
<if test="name != null" >
name,
if>
<if test="price != null" >
price,
if>
<if test="number != null" >
number,
if>
<if test="type != null" >
type,
if>
<if test="no != null" >
no,
if>
trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
if>
<if test="price != null" >
#{price,jdbcType=DOUBLE},
if>
<if test="number != null" >
#{number,jdbcType=INTEGER},
if>
<if test="type != null" >
#{type,jdbcType=VARCHAR},
if>
<if test="no != null" >
#{no,jdbcType=VARCHAR},
if>
trim>
insert>
<select id="countByExample" parameterType="com.ccff.mybatis.model.GoodsExample" resultType="java.lang.Integer" >
select count(*) from goods
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
if>
select>
<update id="updateByExampleSelective" parameterType="map" >
update goods
<set >
<if test="record.id != null" >
id = #{record.id,jdbcType=INTEGER},
if>
<if test="record.name != null" >
name = #{record.name,jdbcType=VARCHAR},
if>
<if test="record.price != null" >
price = #{record.price,jdbcType=DOUBLE},
if>
<if test="record.number != null" >
number = #{record.number,jdbcType=INTEGER},
if>
<if test="record.type != null" >
type = #{record.type,jdbcType=VARCHAR},
if>
<if test="record.no != null" >
no = #{record.no,jdbcType=VARCHAR},
if>
set>
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
if>
update>
<update id="updateByExample" parameterType="map" >
update goods
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=VARCHAR},
price = #{record.price,jdbcType=DOUBLE},
number = #{record.number,jdbcType=INTEGER},
type = #{record.type,jdbcType=VARCHAR},
no = #{record.no,jdbcType=VARCHAR}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
if>
update>
<update id="updateByPrimaryKeySelective" parameterType="com.ccff.mybatis.model.Goods" >
update goods
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
if>
<if test="price != null" >
price = #{price,jdbcType=DOUBLE},
if>
<if test="number != null" >
number = #{number,jdbcType=INTEGER},
if>
<if test="type != null" >
type = #{type,jdbcType=VARCHAR},
if>
<if test="no != null" >
no = #{no,jdbcType=VARCHAR},
if>
set>
where id = #{id,jdbcType=INTEGER}
update>
<update id="updateByPrimaryKey" parameterType="com.ccff.mybatis.model.Goods" >
update goods
set name = #{name,jdbcType=VARCHAR},
price = #{price,jdbcType=DOUBLE},
number = #{number,jdbcType=INTEGER},
type = #{type,jdbcType=VARCHAR},
no = #{no,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
update>
mapper>
生成的Goods实体类如下:
package com.ccff.mybatis.model;
public class Goods {
private Integer id;
private String name;
private Double price;
private Integer number;
private String type;
private String no;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no == null ? null : no.trim();
}
}
生成的GoodsExample实体类如下:
package com.ccff.mybatis.model;
import java.util.ArrayList;
import java.util.List;
public class GoodsExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public GoodsExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andPriceIsNull() {
addCriterion("price is null");
return (Criteria) this;
}
public Criteria andPriceIsNotNull() {
addCriterion("price is not null");
return (Criteria) this;
}
public Criteria andPriceEqualTo(Double value) {
addCriterion("price =", value, "price");
return (Criteria) this;
}
public Criteria andPriceNotEqualTo(Double value) {
addCriterion("price <>", value, "price");
return (Criteria) this;
}
public Criteria andPriceGreaterThan(Double value) {
addCriterion("price >", value, "price");
return (Criteria) this;
}
public Criteria andPriceGreaterThanOrEqualTo(Double value) {
addCriterion("price >=", value, "price");
return (Criteria) this;
}
public Criteria andPriceLessThan(Double value) {
addCriterion("price <", value, "price");
return (Criteria) this;
}
public Criteria andPriceLessThanOrEqualTo(Double value) {
addCriterion("price <=", value, "price");
return (Criteria) this;
}
public Criteria andPriceIn(List<Double> values) {
addCriterion("price in", values, "price");
return (Criteria) this;
}
public Criteria andPriceNotIn(List<Double> values) {
addCriterion("price not in", values, "price");
return (Criteria) this;
}
public Criteria andPriceBetween(Double value1, Double value2) {
addCriterion("price between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andPriceNotBetween(Double value1, Double value2) {
addCriterion("price not between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andNumberIsNull() {
addCriterion("number is null");
return (Criteria) this;
}
public Criteria andNumberIsNotNull() {
addCriterion("number is not null");
return (Criteria) this;
}
public Criteria andNumberEqualTo(Integer value) {
addCriterion("number =", value, "number");
return (Criteria) this;
}
public Criteria andNumberNotEqualTo(Integer value) {
addCriterion("number <>", value, "number");
return (Criteria) this;
}
public Criteria andNumberGreaterThan(Integer value) {
addCriterion("number >", value, "number");
return (Criteria) this;
}
public Criteria andNumberGreaterThanOrEqualTo(Integer value) {
addCriterion("number >=", value, "number");
return (Criteria) this;
}
public Criteria andNumberLessThan(Integer value) {
addCriterion("number <", value, "number");
return (Criteria) this;
}
public Criteria andNumberLessThanOrEqualTo(Integer value) {
addCriterion("number <=", value, "number");
return (Criteria) this;
}
public Criteria andNumberIn(List<Integer> values) {
addCriterion("number in", values, "number");
return (Criteria) this;
}
public Criteria andNumberNotIn(List<Integer> values) {
addCriterion("number not in", values, "number");
return (Criteria) this;
}
public Criteria andNumberBetween(Integer value1, Integer value2) {
addCriterion("number between", value1, value2, "number");
return (Criteria) this;
}
public Criteria andNumberNotBetween(Integer value1, Integer value2) {
addCriterion("number not between", value1, value2, "number");
return (Criteria) this;
}
public Criteria andTypeIsNull() {
addCriterion("type is null");
return (Criteria) this;
}
public Criteria andTypeIsNotNull() {
addCriterion("type is not null");
return (Criteria) this;
}
public Criteria andTypeEqualTo(String value) {
addCriterion("type =", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotEqualTo(String value) {
addCriterion("type <>", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThan(String value) {
addCriterion("type >", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThanOrEqualTo(String value) {
addCriterion("type >=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThan(String value) {
addCriterion("type <", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThanOrEqualTo(String value) {
addCriterion("type <=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLike(String value) {
addCriterion("type like", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotLike(String value) {
addCriterion("type not like", value, "type");
return (Criteria) this;
}
public Criteria andTypeIn(List<String> values) {
addCriterion("type in", values, "type");
return (Criteria) this;
}
public Criteria andTypeNotIn(List<String> values) {
addCriterion("type not in", values, "type");
return (Criteria) this;
}
public Criteria andTypeBetween(String value1, String value2) {
addCriterion("type between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andTypeNotBetween(String value1, String value2) {
addCriterion("type not between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andNoIsNull() {
addCriterion("no is null");
return (Criteria) this;
}
public Criteria andNoIsNotNull() {
addCriterion("no is not null");
return (Criteria) this;
}
public Criteria andNoEqualTo(String value) {
addCriterion("no =", value, "no");
return (Criteria) this;
}
public Criteria andNoNotEqualTo(String value) {
addCriterion("no <>", value, "no");
return (Criteria) this;
}
public Criteria andNoGreaterThan(String value) {
addCriterion("no >", value, "no");
return (Criteria) this;
}
public Criteria andNoGreaterThanOrEqualTo(String value) {
addCriterion("no >=", value, "no");
return (Criteria) this;
}
public Criteria andNoLessThan(String value) {
addCriterion("no <", value, "no");
return (Criteria) this;
}
public Criteria andNoLessThanOrEqualTo(String value) {
addCriterion("no <=", value, "no");
return (Criteria) this;
}
public Criteria andNoLike(String value) {
addCriterion("no like", value, "no");
return (Criteria) this;
}
public Criteria andNoNotLike(String value) {
addCriterion("no not like", value, "no");
return (Criteria) this;
}
public Criteria andNoIn(List<String> values) {
addCriterion("no in", values, "no");
return (Criteria) this;
}
public Criteria andNoNotIn(List<String> values) {
addCriterion("no not in", values, "no");
return (Criteria) this;
}
public Criteria andNoBetween(String value1, String value2) {
addCriterion("no between", value1, value2, "no");
return (Criteria) this;
}
public Criteria andNoNotBetween(String value1, String value2) {
addCriterion("no not between", value1, value2, "no");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
首先,将com.ccff.mybatis.mapper包下的逆向生成的SQL映射文件复制到config/sqlmap文件夹下,具体如下所示:
然后,把该SQL映射文件添加到全局配置文件中,具体配置如下:
<mappers>
<mapper resource="sqlmap/UserMapper.xml"/>
<mapper resource="sqlmap/StudentMapper.xml"/>
<mapper resource="sqlmap/BasketballPlayerMapper.xml"/>
<mapper resource="sqlmap/FinacialMapper.xml"/>
<mapper resource="sqlmap/NewsLabelMapper.xml" />
<mapper resource="sqlmap/LazyLoadingMapper.xml" />
<mapper resource="sqlmap/BookMapper.xml" />
<mapper resource="sqlmap/GoodsMapper.xml" />
mappers>
然后,在com.ccff.mybatis.test包下创建名为“GoodsTest”的测试类,该测试类用于测试通过MyBatis逆向工程生成的数据文件是否可用。初始的测试类具体代码如下:
package com.ccff.mybatis.test;
import com.ccff.mybatis.dao.GoodsMapper;
import com.ccff.mybatis.datasource.DataConnection;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
public class GoodsTest {
private SqlSession sqlSession;
private GoodsMapper goodsMapper;
private DataConnection dataConnection = new DataConnection();
@Before
public void init() {
try {
sqlSession = dataConnection.getSqlSession();
goodsMapper = sqlSession.getMapper(GoodsMapper.class);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void tearDown(){
if (sqlSession != null)
sqlSession.close();
}
}
在测试类中添加名为“TestInsert”的测试方法用于测试插入功能,具体代码如下:
@Test
public void TestInsert(){
Goods goods = new Goods();
goods.setName("三只松鼠坚果");
goods.setNo("SP498713");
goods.setPrice(28.8);
goods.setNumber(100);
goods.setType("食品");
goodsMapper.insert(goods);
sqlSession.commit();
System.out.println("插入了名为:"+goods.getName()+"的商品信息");
}
执行该测试方法,查看输出到控制台的日志信息,说明测试通过。
查看数据库中的goods表,发现刚刚插入的商品信息已经存在了。
这里仅仅测试复杂条件查询功能。在测试类中添加名为“TestSelectByExample”的方法,具体代码如下:
@Test
public void TestSelectByExample(){
GoodsExample goodsExample = new GoodsExample();
//通过Criteria构造查询条件
GoodsExample.Criteria criteria = goodsExample.createCriteria();
//查询条件1:name like 'II'
criteria.andNameLike("%II%");
//查询条件2:price > 1000
criteria.andPriceGreaterThan(1000.00);
//查询条件3:type is not null
criteria.andTypeIsNotNull();
//可能返回多条记录
List<Goods> list = goodsMapper.selectByExample(goodsExample);
for (Goods goods : list){
System.out.println(goods.getId()+":"+goods.getName());
}
}
在测试类中添加名为“TestUpdate”的测试方法用于测试对所有字段进行更新和对个别字段进行更新。具体代码如下:
@Test
public void TestUpdate(){
Goods goods = null;
//对所有字段进行更新,需要先查询出来再更新
goods = goodsMapper.selectByPrimaryKey(5);
goods.setName("三只松鼠夏威夷果");
goodsMapper.updateByPrimaryKey(goods);
sqlSession.commit();
System.out.println("更新id为:"+goods.getId()+"的商品的所有信息");
//对个别字段进行更新:只有传入字段不空才更新,在批量更新中使用此方法,不需要先查询再更新
goods = new Goods();
goods.setId(3);
goods.setName("NIKE Kobe 15");
goodsMapper.updateByPrimaryKeySelective(goods);
sqlSession.commit();
System.out.println("更新id为:"+goods.getId()+"的用户商品名为:"+goods.getName());
}
执行测试方法后,查询输出到控制台的日志信息,说明测试通过。
再次查看mybatis数据库中的goods数据表,发现此时id为3和id为5的商品的商品名均发生了变化。
在测试类中添名为“TestDeleteByPrimaryKey”的方法,用于测试根据主键id删除商品信息的功能,具体代码如下:
@Test
public void TestDeleteByPrimaryKey(){
int deleteId = 5;
goodsMapper.deleteByPrimaryKey(deleteId);
Goods goods = goodsMapper.selectByPrimaryKey(deleteId);
if (goods == null){
System.out.println("删除id为:"+deleteId+"的商品成功,删除成功");
}
}
执行该测试方法后,查看输出到控制台的日志信息如下:
再次查看mybatis数据库中的goods数据表,发现此时id为5的商品信息记录已经不再存在。