Mybatis一对一和一对多关联查询学习

概念

假如遇到一种需求,查询一个人,顺便要求把他的下属职员的信息也搜出来,那么就需要用到关联查询


那么这样查询的话返回值肯定不能是resultType了

得靠resultMap来映射一下


resultMap里的属性标签

<association property=""></association> 代表一对一

<collection property=""></collection>代表一对多


一对一感觉直接表关联就可以先学习一对多

首先实体类

/**
 * @author JAVA
 *	学习关联查询实体类
 */
public class Emp {

	private String name;
	private String job;
	private String Boss;

	private List<Emp> zhazha;
	
	public String getBoss() {
		return Boss;
	}
	public void setBoss(String boss) {
		Boss = boss;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public List<Emp> getZhazha() {
		return zhazha;
	}
	public void setZhazha(List<Emp> zhazha) {
		this.zhazha = zhazha;
	}
	
	
}

下属用实体类建立集合

Controller

	@GetMapping("/learnLinked")
	@ApiOperation(value = "学习关联查询")
	public List<Emp> learnLinked(){
		
		return service.learnLinked();
			
	}

Service

public List<Emp>learnLinked() {
	// TODO Auto-generated method stub
	List<Emp> emp = null;
	
	emp = empMapper.learnLinked();
	
	return emp;
}

Dao

public List<Emp> learnLinked();

Mapper 重点来了

	<select id="learnLinked" resultMap="linked">
		select *
		  from 关联查询学习
		 where boss is null
	</select>
	<resultMap type="com.sola.bean.Emp" id="linked">
		<result property="name" column="NAME" jdbcType="VARCHAR"/>
		<result property="job" column="JOB" jdbcType="VARCHAR"/>
		<result property="boss" column="BOSS" jdbcType="VARCHAR"/>
		<!-- 一对多  查询下级-->       <!-- ofType 指定类型 相当于JavaTYPE-->
		<collection property="zhazha" ofType="com.sola.bean.Emp" column="name" select="learnLinkedBoss">
		</collection>
	</resultMap>
	<select id="learnLinkedBoss" resultMap="linked">
		select *
		  from 关联查询学习 
		 where boss = #{name,jdbcType=VARCHAR}
	</select>

第一条语句很简单 去查询没有上级的人员名单

之后建立了一个resultmap 来映射要关联查询字段

oftype 指定映射java类型 

column 指定要拿哪行去关联查询 以此例子说明  就是拿第一条语句查出的name 去查所对应的下属

select 指定要执行的语句

第二条sql

去查询 上级名是上级sql映射过来的 name



注意点 第一次查询必须为 没有上级的 不然会报错


### The error may exist in file [D:\SpringBootWorkSpace\SpringBootMyBatisAndSwagger\target\classes\mapper\EmpMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: select *     from 关联查询学习    where boss
### Cause: java.sql.SQLSyntaxErrorException: ORA-00920: 无效的关系运算符


; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: ORA-00920: 无效的关系运算符
] with root cause


oracle.jdbc.OracleDatabaseException: ORA-00920: 无效的关系运算符

猜你喜欢

转载自blog.csdn.net/jiulanhao/article/details/80856255