MyBatis之关联关系

梦想与她 提交于 2019-12-04 04:21:35

关联关系

在关系型数据库中,表与表之间很少是独立且没有关系的,大多数表都具有复杂的关系,一张表连接着多张表,在MyBatis中可以进行多表连接处理

关联关系中有1对1、1对多、多对多
在这里插入图片描述

1对1关系

我们有一张员工表(t_emp),一张部门表(t_dept)。员工表中的一条记录对应于部门表中有且仅有一条记录。这就是一对一的关联关系。
查询每个员工的信息及对应的部门信息

1、创建maven项目

在pom.xml文件中导入相关依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zhouym</groupId>
  <artifactId>mybatis-lazy</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>5.1.43</version>
  	</dependency>
  	<dependency>
  		<groupId>org.slf4j</groupId>
  		<artifactId>slf4j-log4j12</artifactId>
  		<version>1.7.25</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis</artifactId>
  		<version>3.4.6</version>
  	</dependency>
  	<dependency>
  		<groupId>junit</groupId>
  		<artifactId>junit</artifactId>
  		<version>4.12</version>
  	</dependency>
  </dependencies>
</project>

2、导入相关资源文件

在这里插入图片描述
db.properties

driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/tb_user?useSSL=true&useUnicode=true&characterEncoding=UTF-8
userName=root
password=123456

log4j.properties

log4j.rootCategory=DEBUG, stdout , R
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
 
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=E:\\tools\\log\\qc.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

mybatis配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!--引入数据库配置信息-->
	<properties resource="db.properties" />
	<typeAliases>
		<!-- typeAlias 具体的给每一个pojo类取别名,如果pojo太多,取名很麻烦 -->
		<!-- <typeAlias type="com.zhouym.pojo.User" alias="user"/> -->
		<!-- 指定一个基础路径 不区分大小写 -->
		<package name="com.zhouym.pojo" />
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driverName}" />
				<property name="url" value="${url}" />
				<property name="username" value="${userName}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<!-- 关联映射文件 -->
	<mappers>
		<!-- package 在接口的方式下使用,接口名称必须和映射文件名称一致 -->
		<package name="com.zhouym.dao" />
	</mappers>
</configuration>

3、POJO类

对应数据库中的表
员工表

package com.zhouym.pojo;

public class Emp {
	private Integer id;
	private String emp_name;
	private Integer dept_id;
	private Dept dept;
	public Emp() {
		super();
	}
	public Emp(Integer id, String emp_name, Integer dept_id) {
		super();
		this.id = id;
		this.emp_name = emp_name;
		this.dept_id = dept_id;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getEmp_name() {
		return emp_name;
	}
	public void setEmp_name(String emp_name) {
		this.emp_name = emp_name;
	}
	public Integer getDept_id() {
		return dept_id;
	}
	public void setDept_id(Integer dept_id) {
		this.dept_id = dept_id;
	}
	public Dept getDept() {
		return dept;
	}
	public void setDept(Dept dept) {
		this.dept = dept;
	}
	@Override
	public String toString() {
		return "Emp [id=" + id + ", emp_name=" + emp_name + ", dept_id=" + dept_id + "]";
	}
	
	
	
}

4、接口类及对应的映射文件

package com.zhouym.dao;

import java.util.List;

import com.zhouym.pojo.Emp;

public interface EmpMapper {
	public List<Emp> query();
}

<?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.zhouym.dao.EmpMapper">
	<!--因为在mybatis配置文件中配置了包名路径,package=“com.zhouym.pojo”,在type中直接写对应的类,不区分大小写-->
 	<resultMap type="emp" id="baseMap">
 		<id property="id" column="id"/>
 		<result property="emp_name" column="emp_name"/>
 		<result property="dept_id" column="dept_id"/>
 		<!-- 一对一关系 -->
 		<association property="dept" javaType="dept">
 			<id property="id" column="did"/>
 			<result property="dept_name" column="dept_name"/>
 			<result property="dept_desc" column="dept_desc"/>
 		</association>
 	</resultMap>
 	<select id="query" resultMap="baseMap">
 		select 
 		t1.id,
 		t1.emp_name,
 		t1.dept_id,
 		t2.id did,
 		t2.dept_name,
 		t2.dept_desc
 		from 
 			t_emp t1 left join t_dept t2 
 				on t1.dept_id = t2.id
 	</select>
</mapper>

5、工具类

DBUtil

package com.zhouym.DBUtil;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DBUtils {
	
	private static InputStream in;
	private static SqlSessionFactory factory = null;
	
	public static SqlSessionFactory getSqlSessionFactory() throws IOException {
		if (factory == null) {
			in = Resources.getResourceAsStream("mybatis-cfg.xml");
			factory  = new SqlSessionFactoryBuilder().build(in);
		}
		
		return factory;
	}
}

6、测试类

package com.zhouym.junit;
import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import com.zhouym.DBUtil.DBUtils;
import com.zhouym.dao.DeptMapper;
import com.zhouym.dao.EmpMapper;
import com.zhouym.pojo.Dept;
import com.zhouym.pojo.Emp;

public class JunitTest {

	@Test
	public void test() throws IOException {
		SqlSessionFactory factory = DBUtils.getSqlSessionFactory();
		SqlSession session = factory.openSession();
		EmpMapper mapper = session.getMapper(EmpMapper.class);
		List<Emp> list = mapper.query();
		for (Emp emp : list) {
			System.out.println(emp);
			System.out.println("===>"+emp.getDept());
		}
	}

}

一对一关系测试结果
在这里插入图片描述

1对多关系

增加部门表

package com.zhouym.pojo;

import java.util.List;

public class Dept {
	private Integer id;
	private String dept_name;
	private String dept_desc;
	private List<Emp> emps;
	@Override
	public String toString() {
		return "Dept [id=" + id + ", dept_name=" + dept_name + ", dept_desc=" + dept_desc +"]";
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getDept_name() {
		return dept_name;
	}

	public void setDept_name(String dept_name) {
		this.dept_name = dept_name;
	}

	public String getDept_desc() {
		return dept_desc;
	}

	public void setDept_desc(String dept_desc) {
		this.dept_desc = dept_desc;
	}

	public List<Emp> getEmps() {
		return emps;
	}

	public void setEmps(List<Emp> emps) {
		this.emps = emps;
	}
	
	
}

部门接口类及映射文件

package com.zhouym.dao;

import java.util.List;

import com.zhouym.pojo.Dept;

public interface DeptMapper {
	public List<Dept> query();
}

<?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">
  <!-- 部门与员工是1对多关系 -->
 <mapper namespace="com.zhouym.dao.DeptMapper">
 	<resultMap type="dept" id="baseMap">
 		<id property="id" column="id"/>
 		<result property="dept_name" column="dept_name"/>
 		<result property="dept_desc" column="dept_desc"/>
 		<collection property="emps" ofType="emp">
 			<id property="id" column="eid"/>
 			<result property="emp_name" column="emp_name"/>
 			<result property="dept_id" column="dept_id"/>
 		</collection>
 	</resultMap>
 	<select id="query" resultMap="baseMap">
 		select 
 			t1.id,
 			t1.dept_name,
 			t1.dept_desc,
 			t2.id eid,
 			t2.emp_name,
 			t2.dept_id
 		from 
 			t_dept t1 
 		left join 
 			t_emp t2 
 		on 
 			t1.id = t2.dept_id
 	</select>
 	
 </mapper>

其他按上面的配置

测试类

package com.zhouym.junit;
import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import com.zhouym.DBUtil.DBUtils;
import com.zhouym.dao.DeptMapper;
import com.zhouym.dao.EmpMapper;
import com.zhouym.pojo.Dept;
import com.zhouym.pojo.Emp;

public class JunitTest {	
	@Test
	public void test1() throws IOException {
		SqlSessionFactory factory = DBUtils.getSqlSessionFactory();
		SqlSession session = factory.openSession();
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		List<Dept> list = mapper.query();
		for (Dept dept : list) {
			System.out.println(dept.getDept_name()+"--->"+dept.getEmps());
		}
	}

}

测试结果
在这里插入图片描述

多对多关系

双向的一对多也是多对多关系
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!