該功能主要是代碼自動生成表對象、mapper以及xml文件(包含了實體的resultMap
映射配置)。html
<!--mybatis之generator插件:生成代碼工具--> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> <scope>test</scope> </dependency>
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;
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 生成成功"); } }
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、Servicejava
//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; }
一、本文參考(未使用xml配置):CodeGenerator.javamysql
二、官文(使用xml配置)使用:xml配置參數方式git
三、mybatis-generator使用方式github
四、mybatis-generator配置參數說明spring