首页 > 其他 > 详细

mybatis关联查询多对一

时间:2020-04-25 20:49:41      阅读:63      评论:0      收藏:0      [点我收藏+]

一、实体类(getset方法,toString,构造方法忽略)

public class Dept {
	private Integer deptid;
	private String dname;
	private String dloc;
}
public class Emp {
	private Integer empid;
	private String ename;
	private String esex;
	private Date ehiredate;
	private Double esal;
	private Dept dept;
}

二、接口方法,以下用了两种方法(推荐第一种)

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

三、xml文件

EmpMapper.xml

<mapper namespace="com.gx.mapper.EmpMapper">
	
	<resultMap type="Emp" id="BaseEmp">
		<id property="empid" column="empid" />
		<result property="ename" column="ename"/>
		<result property="esex" column="esex"/>
		<result property="ehiredate" column="ehiredate"/>
		<result property="esal" column="esal"/>
	
	</resultMap>
	<resultMap type="Emp" id="myEmp" extends="BaseEmp">
		<!-- 建立关系 
			property="dept"   指emp里面的dept属性
			javaType 指emp属性的类型
		-->
		<association property="dept"  javaType="com.gx.domain.Dept" >
			<id property="deptid" column="deptid"/>
			<result property="dname" column="dname"/>
			<result property="dloc" column="dloc"/>
		</association>
	</resultMap>
	
	<select id="selectAllEmp"  resultMap="myEmp">
		select * from emp inner join dept using(deptid)
	</select>
	
		<resultMap type="Emp" id="myEmp2" extends="BaseEmp">
		<!-- 建立关系 
			property="dept"   指emp里面的dept属性
			javaType 指emp属性的类型
			column="deptid" 从当前的结果集里面取出deptid,传给com.gx.mapper.DeptMapper.selectDeptById
		-->
		<association property="dept"  column="deptid" select="com.gx.mapper.DeptMapper.selectDeptById">
		</association>
	</resultMap>
		<select id="selectAllEmp2"  resultMap="myEmp2">
		select * from emp inner join dept using(deptid)
	</select>
	
</mapper>

DeptMapper.xml

<mapper namespace="com.gx.mapper.DeptMapper">
	<!--  根据部门编号查询部门信息-->
	<select id="selectDeptById" resultType="Dept">
		select * from dept where deptid=#{deptid}
	</select>
	
</mapper>

四、测试

public class myTest {
	SqlSession session = MyBatisUtils.openSession();
	EmpMapper empMapper = session.getMapper(EmpMapper.class);
	
	@Test
	public void selectAllEmp() {
		List<Emp> list = empMapper.selectAllEmp();
		for (Emp emp : list) {
			System.out.println(emp);
		}
		MyBatisUtils.closeSession(session);
	}
	
	@Test
	public void selectAllEmp2() {
		List<Emp> list = empMapper.selectAllEmp2();
		for (Emp emp : list) {
			System.out.println(emp);
		}
		MyBatisUtils.closeSession(session);
	}
}

其他方法:可以在Emp实体类中添加dname,dloc,

select * from emp inner join dept using(deptid)

用直接查询出来

mybatis关联查询多对一

原文:https://www.cnblogs.com/97guoxiang/p/12774881.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!