一、概述
Mybatis官方提供逆向工廠浊竟,可以針對單表自動生成mybatis
執(zhí)行所需要的代碼(如mapper.java怨喘、mapper.xml、pojo
)振定。這里有很多方法可選:
這里我們建議使用第四種方式或者
MyEclipse
插件方式必怜,最好是前者,因為不受開發(fā)工具影響后频。使用前者時需要下載一個工具包mybatis-generator-core-1.3.2.jar
梳庆。
二、使用工具逆向生成相關(guān)代碼
首先我們建立一個java
工程(mybatis-generator
)卑惜,然后導(dǎo)入mybatis
的相關(guān)jar包和上面提到的工具包膏执。然后編寫用于生成相關(guān)類的配置文件:
generatorConfig.xml
<?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>
<!-- 是否去除自動生成的注釋 ture:是 false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 數(shù)據(jù)庫連接的信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3305/mybatis"
userId="root"
password="walp1314">
</jdbcConnection>
<!-- oracle -->
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:mybatis"
userId="root"
password="walp1314">
</jdbcConnection> -->
<!-- 默認(rèn)false,把JDBC DECIMAL和NUMERIC類型解析為Integer残揉,為true時解析為java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成pojo類的位置 -->
<javaModelGenerator targetPackage="cn.itcast.ssm.pojo"
targetProject=".\src">
<!-- enableSubPackages:是否讓schame作為包的后綴 -->
<property name="enableSubPackages" value="false"/>
<!-- 從數(shù)據(jù)庫返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper映射成文件的位置 -->
<sqlMapGenerator targetPackage="cn.itcast.ssm.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否讓schame作為包的后綴 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator targetPackage="cn.itcast.ssm.mapper"
type="XMLMAPPER" targetProject=".\src">
<!-- enableSubPackages: 是否讓schame作為包的后綴-->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定數(shù)據(jù)庫表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table>
<table tableName="user"></table>
<!-- <table schema="" tableName="sys_user"></table>
<table schema="" tableName="sys_role"></table>
<table schema="" tableName="sys_permission"></table>
<table schema="" tableName="sys_user_role"></table>
<table schema="" tableName="sys_role_permission"></table> -->
<!-- 有些表的字段需要指定java類型 -->
<!-- <table schema="" tableName="">
<columnOverride column="" javaType=""/>
</table> -->
</context>
</generatorConfiguration>
編寫一個工具類生成相關(guān)代碼:
GeneratorSqlmap.java
package cn.itcast.ssm.util;
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) {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
說明:這個類的是直接從官網(wǎng)上找到的胧后,這里不比關(guān)心其實現(xiàn)原理。運行此類我們就可以發(fā)現(xiàn)在工程中生成了相關(guān)的類抱环。
注意:一般我們都是單獨建一個工程壳快,專門用來逆向生成相關(guān)代碼,然后將這些代碼拷貝到項目工程中镇草,這樣比較安全眶痰,避免出現(xiàn)同名文件的覆蓋問題。這里將代碼拷貝到了工程
spring-mybatis02
梯啤。
三竖伯、使用生成的代碼
測試ItemsMapper.java
中的方法:
package cn.itcast.ssm.mapper;
import cn.itcast.ssm.pojo.Items;
import cn.itcast.ssm.pojo.ItemsExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ItemsMapper {
int countByExample(ItemsExample example);
int deleteByExample(ItemsExample example);
int deleteByPrimaryKey(Integer id);
int insert(Items record);
int insertSelective(Items record);
List<Items> selectByExampleWithBLOBs(ItemsExample example);
List<Items> selectByExample(ItemsExample example);
Items selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);
int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);
int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);
int updateByPrimaryKeySelective(Items record);
int updateByPrimaryKeyWithBLOBs(Items record);
int updateByPrimaryKey(Items record);
}
測試方法ItemsMapperTest.java
package cn.itcast.ssm.mapper;
import static org.junit.Assert.*;
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.pojo.Items;
import cn.itcast.ssm.pojo.ItemsExample;
public class ItemsMapperTest {
private ApplicationContext applicationContext;
private ItemsMapper itemsMapper;//這里我們使用的是spring的自動掃描后注入的
@Before
public void setUp()throws Exception{
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
}
//根據(jù)主鍵刪除
@Test
public void testDeleteByPrimaryKey() {
}
@Test
public void testInsert() {
//構(gòu)造Items對象
Items items = new Items();
items.setName("手機");
items.setPrice(1999f);
itemsMapper.insert(items);
}
//自定義條件查詢
@Test
public void testSelectByExample() {
ItemsExample itemsExample = new ItemsExample();
//通過criteria構(gòu)造查詢條件
ItemsExample.Criteria criteria = itemsExample.createCriteria();
criteria.andNameEqualTo("臺式機");//這就是我們添加的查詢條件
//可能返回多天記錄
List<Items> list = itemsMapper.selectByExample(itemsExample);
for(Items tmp : list){
System.out.println(tmp.getName());
}
}
//根據(jù)主鍵查詢
@Test
public void testSelectByPrimaryKey() {
Items items = itemsMapper.selectByPrimaryKey(1);
System.out.println(items.getName());
}
//更新
@Test
public void testUpdateByPrimaryKey() {
//對所有字段進(jìn)行更新,需要先查詢出來再更新
Items items = itemsMapper.selectByPrimaryKey(1);
items.setName("水杯");
itemsMapper.updateByPrimaryKey(items);
//如果傳入字段不為空才更新,一般用在批量更新中七婴,不需要先查詢再更新
//itemsMapper.updateByPrimaryKeySelective(items);
}
}
說明:這里我們是對相關(guān)方法的一個簡要測試祟偷。其他內(nèi)容還需要再研究。