MyBatis实现级联查询及逆向生成
一,级联查询
1、级联查询 N-1
以多的一方为主表
接口
//级联查询 N-1
List<Emp> selectEmp(Map map);
映射文件
<!--级联查询 N-1 -->
<resultMap id="emp_Dept" type="emp">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="sex" property="sex"/>
<result column="salary" property="salary"/>
<result column="bonus" property="bonus"/>
<result column="birth" property="birth"/>
<result column="hiredate" property="hiredate"/>
<result column="leader" property="leader"/>
<result column="deptid" property="deptid"/>
<association property="dept" javaType="dept">
<id column="id" property="id"/>
<result column="dname" property="dname"/>
</association>
</resultMap>
<select id="selectEmp" resultMap="emp_Dept" parameterType="map">
select * from emp e left join dept d on e.deptid=d.id
<where>
<if test="name!=null">
name like "%"#{name}"%"
</if>
</where>
limit #{start},#{size}
</select>
一的一方的数据封装使用association标签
使用JavaType固定搭配
对应javabean中的属性
测试类
SqlSession session=null;
@Before
public void init() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(is);
session=factory.openSession();
}
//级联查询N-1
@Test
public void selectEmp() {
HashMap map = new HashMap();
map.put("name","关");
map.put("start",0);
map.put("size",3);
List<Emp> emps = session.getMapper(EmpMapper.class).selectEmp(map);
System.out.println(emps);
}
@After
public void destory(){
if (session!=null){
try {
session.commit();
}catch (Exception e){
session.rollback();
}finally {
session.close();
}
}
}
2、级联查询 1-N
以一的一方为主表
映射文件
<!--级联查询 1-N -->
<resultMap id="dept_Emp" type="dept">
<id column="did" property="id"/>
<result column="dname" property="dname"/>
<collection property="emps" ofType="emp">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="sex" property="sex"/>
<result column="salary" property="salary"/>
<result column="bonus" property="bonus"/>
<result column="birth" property="birth"/>
<result column="hiredate" property="hiredate"/>
<result column="leader" property="leader"/>
<result column="deptid" property="deptid"/>
</collection>
</resultMap>
<select id="selectDept" resultMap="dept_Emp" parameterType="map">
select e.*,d.id did,d.dname from emp e left join dept d on e.deptid=d.id
<where>
<if test="dname!=null">
dname like "%"#{dname}"%"
</if>
</where>
limit #{start},#{size}
</select>
多的一方的数据使用collection标签封装
固定搭配 ofType
对应javabean中的属性
测试类
SqlSession session=null;
@Before
public void init() throws IOException {
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(is);
session=factory.openSession();
}
//级联查询1-N
@Test
public void selectDept() {
HashMap map = new HashMap();
map.put("dname","蜀");
map.put("start",0);
map.put("size",3);
List<Dept> depts = session.getMapper(EmpMapper.class).selectDept(map);
System.out.println(depts);
}
@After
public void destory(){
if (session!=null){
try {
session.commit();
}catch (Exception e){
session.rollback();
}finally {
session.close();
}
}
}
总结
一对多 以一的一方为主表; 多对一 以多的一方为主表
Association 封装一的一方的数据,固定类型搭配 javaType。
collection封装多的一方的数据,固定类型搭配 ofType。
二、逆向生成
1、.Pom.xml中的依赖
<!--逆向生成配置-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!--逆向生成带分页的插件-->
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.0.5</version>
</dependency>
<!--日志输出-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
2、逆向生成配置文件 MyBatisGenerator.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="DB2Tables" targetRuntime="MyBatis3">
<!--分页插件-->
<plugin type="com.itfsw.mybatis.generator.plugins.LimitPlugin"/>
<commentGenerator>
<!-- 是否去除注释,true表示是,false否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 1.连接数据库信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/k9503?characterEncoding=UTF-8"
userId="root"
password="171009">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 2.pojo类的生成配置 targetPackage表示目标文件夹
targetProject表示当前目标文件夹所放置的目标地址
-->
<javaModelGenerator targetPackage="com.pojo" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 3.sql映射文件生成配置 -->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 4.mapper接口配置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 5.数据库表和实体类映射 -->
<table tableName="emp" domainObjectName="Emp">
</table>
<table tableName="dept" domainObjectName="Dept">
</table>
</context>
</generatorConfiguration>
此配置文件必须放在整个工程的目录下
可能需要修改的部分:
- 数据库连接信息
- 实体类的生成路径
- Sql映射文件的生成路径
- Mapper接口的生成路径
- 数据库表 表名 和 关联的 实体类的类名
3、自动生成的测试方法
@Test
public void create() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("MybatisGenerator.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);
}
注意
- 核心配置文件 sqlMapConfig.xml的导入 db.properties 数据库四大参数配置文件的导入
- 核心配置文件中 对映射文件的关联
在准备工作都完成之后,执行测试方法,即可自动生成成javabean 和 接口 以及 映射文件
在生成的pojo中还有一个Example类 该类封装了所有属性的各种条件查询
通过example对象创建criteria对象,该对象通过sql拼接的方式 实现条件的封装,所以开发人员只需要调用相应
方法即可完成带条件的增删改查。
逆向工程没有提供 分页查询 和两个表的 级联查询 这一块需要我们自己去补充添加。
4、测试类
@Test//修改
public void update() {
Emp emp = new Emp();
emp.setName("虚竹");
EmpExample example = new EmpExample();
EmpExample.Criteria criteria = example.createCriteria();
criteria.andNameLike("%小%");
int i = session.getMapper(EmpMapper.class).updateByExampleSelective(emp, example);
System.out.println(i);
}
@Test//条件查询
public void select(){
EmpExample example = new EmpExample();
EmpExample.Criteria criteria = example.createCriteria();
criteria.andNameLike("%%");
example.limit(5,5);
List<Emp> emps = session.getMapper(EmpMapper.class).selectByExample(example);
System.out.println(emps);
}
@Test//动态新增
public void insert(){
Emp emp = new Emp();
emp.setName("萧寒");
emp.setSex("男");
emp.setAge(22);
emp.setBonus(1500.00);
int i = session.getMapper(EmpMapper.class).insertSelective(emp);
System.out.println(i);
}
@Test//删除
public void delete(){
EmpExample example = new EmpExample();
EmpExample.Criteria criteria = example.createCriteria();
criteria.andNameLike("%彭%");
int i = session.getMapper(EmpMapper.class).deleteByExample(example);
System.out.println(i);
}