前言
前面我们使用Mybatis的时候,一般的流程都是先在数据库中创建库表,然后在java工程中写对应的实体类,再写Mybatis的配置文件(包括SqlMapConfig.xml和Mapper.xml),最后再写dao层的业务代码。简直是太麻烦了,我们可以利用Mybatis的逆向工程,只在mysql中创建好库表,就能自动为我们生成3个java文件和1个xml文件。3个java文件包括实体类,具有CRUD方法的Mapper接口,为CRUD添加条件的辅助类,1个xml文件就是Mapper配置文件。
正文
一,逆向工程代码
这个工程是大神写的,我们拿来用就行了,结构图:
执行文件根据配置文件生成相应代码。我们来看“配置文件”和“执行文件”:
1,配置文件
<?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>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/user" userId="root"
password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.taotao.pojo"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.taotao.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.taotao.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="tb_content"></table>
</context>
</generatorConfiguration>
2,执行文件
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 GeneratorSqlmap {
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
源代码地址:链接:http://pan.baidu.com/s/1slhR9oT 密码:lkue
二,生成的代码什么样
1,实体类
package com.jimmy.domain;
public class User3 {
private Integer id; // 字段跟数据库中的一样
private String username;
private String password;
// 省略get,set方法
}
2,Mapper接口
其中包含了很多类型的CRUD方法,比我们自己写的好。
值得注意的是:方法依赖xxxExample类型的变量传入条件。若不指定条件则按无条件来操作。
package com.jimmy.mapper;
import com.jimmy.domain.User3;
import com.jimmy.domain.User3Example;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface User3Mapper {
int countByExample(User3Example example); // 指定条件统计
int deleteByExample(User3Example example); // 指定条件删除
int deleteByPrimaryKey(Integer id); // 根据主键删除
int insert(User3 record); // 添加
int insertSelective(User3 record);
List<User3> selectByExample(User3Example example); // 指定条件查询
User3 selectByPrimaryKey(Integer id); // 根据主键查询
int updateByExampleSelective(@Param("record") User3 record, @Param("example") User3Example example); // 指定条件更新
int updateByExample(@Param("record") User3 record, @Param("example") User3Example example); // 指定条件更新
int updateByPrimaryKeySelective(User3 record); // 根据主键更新
int updateByPrimaryKey(User3 record); // 根据主键更新
}
3,Example条件,不再贴代码
4,Mapper.xml , 其中是Mapper接口中方法一一对应的标签(select,insert,delete,update)。
三,对生成的代码进行测试:
首先,创建一个Spring和Mybatis整合的工程,见上一篇博客。
然后,启动Spring容器,并根据类型从容器中得到Mapper接口的代理对象。
最后,调用Mapper接口中的方法(可指定条件)。
测试代码使用的主体类跟上面不一样,但同样说明问题。
public class Test {
@org.junit.Test
public void test(){
ApplicationContext aa = new ClassPathXmlApplicationContext("spring/*.xml");
TbUserMapper tbUserMapper = aa.getBean(TbUserMapper.class);
TbUserExample example = new TbUserExample(); // 条件为空
List<TbUser> selectByExample = tbUserMapper.selectByExample(example );
for (TbUser tbUser : selectByExample) {
System.out.println(tbUser.getUsername());
}
}
@org.junit.Test
public void test2(){
ApplicationContext aa = new ClassPathXmlApplicationContext("spring/*.xml");
TbUserMapper tbUserMapper = aa.getBean(TbUserMapper.class);
TbUserExample example = new TbUserExample();
Criteria createCriteria = example.createCriteria(); // 创建条件对象
createCriteria.andIdBetween(14L, 16L); // 设置条件
List<TbUser> selectByExample = tbUserMapper.selectByExample(example );
for (TbUser tbUser : selectByExample) {
System.out.println(tbUser.getUsername());
}
}
}
总结
mybatis逆向生成的代码即方便,又好用,在实际开发中很有用。