MyBatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表自动生成mybatis执行所需要的代码(包括mapper.xml、mapper.java、po..)。一般在开发中,ql表的结构后, 我们就可以利用逆向工程直接生成相应的Dao和JavaBean代码, 这样能够大大减少我们平时开发的工作量
首先我们要新建一个java工程,这个工程专门用来使用逆向工程生成代码的。有些人可能会问,为什么要新建一个工程呢?直接在原来工程中你想生成不就可以了么?确实是这样,可以在原来的工程中生成,但是有风险,因为MyBatis是根据配置文件来生成的(下面会说到),如果生成的路径中有相同的文件,那么就会覆盖原来的文件,这样会有风险。所以开发中一般都会新建一个java工程来生成,然后将生成的文件拷贝到自己的工程中,这也不麻烦,而且很安全。
下面是几种常见的使用方式: 在这里就介绍一种最简单的,java程序生成(个人推荐使用)
第一步:导入需要的jar包
第二步:
准备逆向工程配置文件genreatorConfig.xml,名字无所谓,只要在java程序中作为file传入就好:
<?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/mybaties" userId="root"
password="123">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
userId="yycg"
password="yycg">
</jdbcConnection> -->
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="cn.itcast.ssm.po"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="cn.itcast.ssm.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.itcast.ssm.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table>
<table tableName="user"></table>
<!-- 有些表的字段需要指定java类型
<table schema="" tableName="">
<columnOverride column="" javaType="" />
</table> -->
</context>
</generatorConfiguration>
第三步:准备java程序,在开发文档首页,粘贴一下就好了:
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("generatorSqlmap.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();
}
}
}
第四步:运行java程序成功之后刷新一下,就会发现生成的代码:
注意:生成的mapper.xml的命名空间一定要和项目的相同,不相同的话,导入项目之后比较麻烦
第五部:导入项目进行测试,为了方便,只导入了Items的mapper以及相关的文件
生成测试代码:在mapper.java右键》new》Junit Test case
选择了部分方法进行了测试
package cn.itcast.ssm.mapper;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsExample;
public class ItemsMapperTest {
private ApplicationContext applicationContext;
private ItemsMapper itemsMapper;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
}
@Test
public void testInsert() {
Items items=new Items();
items.setName("水杯");
items.setPrice(500f);
items.setCreatetime(new Date());
itemsMapper.insert(items);
}
@Test
public void testSelectByExample() {
// 自定义查询
ItemsExample itemsExample = new ItemsExample();
// 通过criteria构造条件
ItemsExample.Criteria criteria = itemsExample.createCriteria();
criteria.andNameEqualTo("笔记本");
// 可能返回的是多条记录
List<Items> list = itemsMapper.selectByExample(itemsExample);
System.out.println(list);
}
@Test
public void testSelectByPrimaryKey() {
Items items = itemsMapper.selectByPrimaryKey(1);
System.out.println(items);
}
@Test
public void testUpdateByPrimaryKey() {
Items items=itemsMapper.selectByPrimaryKey(4);
items.setName("手机");
//updateByPrimaryKey先查询后更新
itemsMapper.updateByPrimaryKey(items);
//如果传入字段不为空才更新,一般应用于批量生产中,不需要先查询在更新
// itemsMapper.updateByPrimaryKeySelective(items);
}
}
里边的标签有不懂的参考MyBatis Generator 详解:http://blog.csdn.net/weixin_38009266/article/details/77865230