-
简介
-
正向生成
table ==> javaBean ==> BeanDao ==> dao.xml
-
逆向生成
根据数据表 table,逆向分析数据表,自动生成 javaBean、BeanDao 、dao.xml
-
-
Mybatis 依赖
<!-- MyBatis 逆向工程 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
- 生成配置
<?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>
<!--Generator提供内置插件,提供limit相关的操作 -->
<!-- 参见:http://mybatis.org/generator/reference/plugins.html -->
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 不生成注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库连接信息 -->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定JavaBean生成的位置 -->
<javaModelGenerator
targetPackage="com.moc.crud.bean"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 指定映射文件生成的位置 -->
<sqlMapGenerator
targetPackage="mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 指定dao接口生成的位置,mapper接口 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.moc.crud.dao"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定每个表的生成策略 -->
<table tableName="tb_emp" domainObjectName="Employee"></table>
<table tableName="tb_dept" domainObjectName="Department"></table>
</context>
</generatorConfiguration>
- 运行生成
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;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MBGTest {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.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);
}
}
-
生成结果
-
新增关联查询
MBG自动生成的查找都是单表查询,如果遇到有外键连接的,需要添加多表的查询方法。
- 在实体类中添加 外键关联的类 的属性
- 增加能够查询 外加关联的类 属性的方法
- 映射文件中添加查询方法
// 外键关联的属性 -- 外键属性dId 连接表查询得到
private Department department;
// 添加方法
// 条件查询
List<Employee> selectByExampleWithDept(EmployeeExample example);
// 主键查询
Employee selectByPrimaryKeyWithDept(Integer empId);
<!-- List<Employee> selectByExampleWithDept(EmployeeExample example); -->
<sql id="WithDept_Column_List">
e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
</sql>
<resultMap id="WithDeptResultMap" type="com.moc.crud.bean.Employee">
<id column="emp_id" jdbcType="INTEGER" property="empId" />
<result column="emp_name" jdbcType="VARCHAR" property="empName" />
<result column="gender" jdbcType="VARCHAR" property="gender" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="d_id" jdbcType="INTEGER" property="dId" />
<association property="department" javaType="com.moc.crud.bean.Department">
<id column="dept_id" property="deptId" />
<result column="dept_name" property="deptName" />
</association>
</resultMap>
<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
from tb_emp e
left join tb_dept d on e.`d_id`=d.`dept_id`
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<!-- Employee selectByPrimaryKeyWithDept(Integer empId); -->
<select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List" />
from tb_emp e
left join tb_dept d on e.`d_id`=d.`dept_id`
where emp_id = #{empId,jdbcType=INTEGER}
</select>
- 批量查询、测试
- spring配置文件添加 Bean
<!-- Mybatis内置的ExecutorType:
默认的是simple:该模式下它为每个语句的执行创建一个新的预处理语句,单条提交sql;
batch:模式重复使用已经预处理的语句,并且批量执行所有更新语句,批量时使用
-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
<constructor-arg name="executorType" value="BATCH" />
</bean>
- 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
public class EmployeeMapperTest {
@Autowired
EmployeeMapper employeeMapper;
@Autowired
SqlSession sqlSession;
/**
* 批量插入测试
*/
@Test
public void TestBatchInsert() {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
for (int i = 0; i < 1000; i++) {
String uuid = UUID.randomUUID().toString().substring(0, 5) + i;
mapper.insertSelective(new Employee(null, uuid, "F", uuid + "@moc.com", 2));
}
}
/**
* 单条插入测试
*/
@Test
public void insertSelective() {
employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "Jerry@moc.com", 2));
}
}
- SpringBoot中的使用
- Pom文件中添加依赖
<!-- Spring与MyBatis的整合 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- build中加入Mybatis Generator插件 -->
<build>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<!-- 插件依赖的数据库驱动 -->
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
- application.yaml 文件中添加配置
mybatis:
configuration:
map-underscore-to-camel-case: true # 驼峰转换规则
type-aliases-package: com.moc.community.mapper # mapper接口所在路径
mapper-locations: classpath:mapper/*.xml # mapper的xml文件路径
- SpringBoot程序入口类添加
@MapperScan注解
@SpringBootApplication
@MapperScan("com.moc.community.mapper")
public class CommunityApplication {
public static void main(String[] args) {
SpringApplication.run(CommunityApplication.class, args);
}
}
- 在 resources 资源目录下,创建
generatorConfig.xml
文件作为生成配置文件,见第3步。 - 在cmd中,cd到当前项目路径,执行如下 mvn 命令
mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate