1、概述
该功能主要是代码自动生成表对象、mapper以及xml文件(包含了实体的resultMap
映射配置)。
2、集成步骤
- pom.xml文件:引入mybatis-generator包
<!--mybatis之generator插件:生成代码工具--> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> <scope>test</scope> </dependency>
- db.sql:创建t_order表
CREATE TABLE `t_order` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `user_id` bigint(20) NOT NULL, `order_money` decimal(20,3) NOT NULL COMMENT '金额', `order_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
- MybatisCodeGenerator.java:生成代码Main
import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.*; import org.mybatis.generator.internal.DefaultShellCallback; import java.util.ArrayList; import java.util.List; /** * http://www.jianshu.com/p/e09d2370b796 * http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/7.UseMBG.md * 用于生成Mybatis代码:domain、mapper、xml文件 */ public class MybatisCodeGenerator { //JDBC配置,请修改为你项目的实际配置 private static final String JDBC_URL = "jdbc:mysql://localhost:3306/spring-boot-demo"; private static final String JDBC_USERNAME = "root"; private static final String JDBC_PASSWORD = "root"; private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; public static final String BASE_PACKAGE = "com.ss.quickStart";//项目基础包名称,根据自己公司的项目修改 public static final String MAPPER_INTERFACE_REFERENCE = BASE_PACKAGE + ".core.Mapper";//Mapper插件基础接口的完全限定名 public static final String DOMAIN_PACKAGE = BASE_PACKAGE + ".domain";//表对象 public static final String MAPPER_PACKAGE = BASE_PACKAGE + ".dao";//dao所在 private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径 private static final String JAVA_PATH = "/src/main/java"; //java文件路径 private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径 public static void main(String[] args) { genDomainAndMapper("t_order","Order"); } public static void genDomainAndMapper(String tableName,String domainName){ Context context = new Context(ModelType.FLAT); context.setId("ss"); context.setTargetRuntime("MyBatis3Simple"); context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`"); context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`"); //数据库连接设置 JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration(); jdbcConnectionConfiguration.setConnectionURL(JDBC_URL); jdbcConnectionConfiguration.setUserId(JDBC_USERNAME); jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD); jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME); context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration); //使用MapperPlugin生成 PluginConfiguration pluginConfiguration = new PluginConfiguration(); pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin"); pluginConfiguration.addProperty("mappers", MAPPER_INTERFACE_REFERENCE); context.addPluginConfiguration(pluginConfiguration); //生成表对象 JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration(); javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH); javaModelGeneratorConfiguration.setTargetPackage(DOMAIN_PACKAGE); context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration); //生成xml SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration(); sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH); sqlMapGeneratorConfiguration.setTargetPackage("mapper"); context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration); //生成dao对象 JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration(); javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH); javaClientGeneratorConfiguration.setTargetPackage(MAPPER_PACKAGE); javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER"); context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration); TableConfiguration tableConfiguration = new TableConfiguration(context); tableConfiguration.setTableName(tableName); tableConfiguration.setDomainObjectName(domainName); tableConfiguration.setGeneratedKey(new GeneratedKey("id", "JDBC", true, null)); context.addTableConfiguration(tableConfiguration); List<String> warnings; MyBatisGenerator generator; try { Configuration config = new Configuration(); config.addContext(context); config.validate(); boolean overwrite = true; DefaultShellCallback callback = new DefaultShellCallback(overwrite); warnings = new ArrayList<String>(); generator = new MyBatisGenerator(config, callback, warnings); generator.generate(null); } catch (Exception e) { throw new RuntimeException("生成Model和Mapper失败", e); } if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) { throw new RuntimeException("生成Model和Mapper失败:" + warnings); } System.out.println(domainName + ".java 生成成功"); System.out.println(domainName + "Mapper.java 生成成功"); System.out.println(domainName + "Mapper.xml 生成成功"); } }
3、实例运行
- 执行MybatisCodeGenerator.java:生成三个对象
-
package com.ss.quickStart.domain; import java.math.BigDecimal; import java.util.Date; import javax.persistence.*; @Table(name = "t_order") public class Order { /** * 主键 */ @Id @GeneratedValue(generator = "JDBC") private Long id; @Column(name = "user_id") private Long userId; /** * 金额 */ @Column(name = "order_money") private BigDecimal orderMoney; @Column(name = "order_time") private Date orderTime; /** * 获取主键 * * @return id - 主键 */ public Long getId() { return id; } /** * 设置主键 * * @param id 主键 */ public void setId(Long id) { this.id = id; } /** * @return user_id */ public Long getUserId() { return userId; } /** * @param userId */ public void setUserId(Long userId) { this.userId = userId; } /** * 获取金额 * * @return order_money - 金额 */ public BigDecimal getOrderMoney() { return orderMoney; } /** * 设置金额 * * @param orderMoney 金额 */ public void setOrderMoney(BigDecimal orderMoney) { this.orderMoney = orderMoney; } /** * @return order_time */ public Date getOrderTime() { return orderTime; } /** * @param orderTime */ public void setOrderTime(Date orderTime) { this.orderTime = orderTime; } }
package com.ss.quickStart.dao; import com.ss.quickStart.core.Mapper; import com.ss.quickStart.domain.Order; public interface OrderMapper extends Mapper<Order> { }
<?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.ss.quickStart.dao.OrderMapper"> <resultMap id="BaseResultMap" type="com.ss.quickStart.domain.Order"> <!-- WARNING - @mbg.generated --> <id column="id" jdbcType="BIGINT" property="id" /> <result column="user_id" jdbcType="BIGINT" property="userId" /> <result column="order_money" jdbcType="DECIMAL" property="orderMoney" /> <result column="order_time" jdbcType="TIMESTAMP" property="orderTime" /> </resultMap> </mapper>
编写Controller、Service
//localhost:8080/user/addOrder.do?money=998 @RequestMapping("user/addOrder.do") public Boolean addOrder(BigDecimal money){ Order order = new Order(); order.setUserId(1L); order.setOrderMoney(money); return userService.addOrder(order); }
public Boolean addOrder(Order order){ orderMapper.insert(order); return true; }
- http://localhost:8080/user/addOrder.do?money=998
4、参考资料
1、本文参考(未使用xml配置):CodeGenerator.java
2、官文(使用xml配置)使用:xml配置参数方式