MyBatis 屬於半自動 ORM,手寫 Mapper 映射文件工作量大且易出錯。官方提供 MyBatis Generator (MBG),可針對單表自動生成 Mapper 接口、XML 映射文件、實體類(POJO)及 Example 條件類,極大提升開發效率。企業級開發中常用「數據庫表 → Java 代碼」的逆向工程模式。
mybatis-generator-core-1.3.2-bundle.zip創建獨立生成工程,生成的代碼再複製到主項目,避免覆蓋源文件。核心配置文件 generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "https://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<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="1234">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="cn.edu.hpu.ssm.po" targetProject=".\src">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="cn.edu.hpu.ssm.mapper" targetProject=".\src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.edu.hpu.ssm.mapper" targetProject=".\src">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定生成的表 -->
<table tableName="items"/>
<table tableName="orders"/>
<table tableName="orderdetail"/>
<table tableName="user"/>
</context>
</generatorConfiguration>
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<>();
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 {
new GeneratorSqlmap().generator();
}
}
將生成的 ItemsMapper.java、ItemsMapper.xml、Items.java、ItemsExample.java 複製到主項目對應包下,配置 Spring 掃描 Mapper 接口後即可使用。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext.xml")
public class ItemsMapperTest {
@Autowired
private ItemsMapper itemsMapper;
@Test
public void testInsert() {
Items items = new Items();
items.setName("iPhone-5S");
items.setPrice(3999f);
items.setDetail("正品行貨");
items.setPic("sdasd.jpg");
items.setCreatetime(new Date());
itemsMapper.insert(items);
}
@Test
public void testSelectByExample() {
ItemsExample example = new ItemsExample();
example.createCriteria().andNameEqualTo("電視機");
List<Items> list = itemsMapper.selectByExample(example);
list.forEach(it -> System.out.println(it.getId() + ":" + it.getName()));
}
@Test
public void testSelectByPrimaryKey() {
Items items = itemsMapper.selectByPrimaryKey(1);
System.out.println(items.getName());
}
@Test
public void testUpdateByPrimaryKey() {
Items items = itemsMapper.selectByPrimaryKey(1);
items.setName("iPhone");
itemsMapper.updateByPrimaryKey(items);
}
}
generatorConfig.xml 納入版本管理,記錄表結構變更歷史。NUMBER 對應 BigDecimal)使用 <columnOverride> 指定 Java 類型。suppressAllComments=true 減少生成代碼體積,避免時間戳導致無意義 diff。