欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mybatis入门(三)---ResultMap

程序员文章站 2022-07-13 17:02:06
...

下面将介绍一个resultMap最基本的用法-----一对一/has a 关系

 

承接上篇文章

 

1.新建表t_dept,并修改表t_user.建表语句如下

create table t_dept (deptno varchar2(11),deptname varchar2(22));
alter table t_dept add constraints pk_deptno primary key(deptno);
alter table t_user add(deptno varchar2(11));
insert into t_dept values('1111','dept1');
update t_user set deptno = '1111'; 

 2.添加实体类Dept.java

package com.mybatis.test.vo;
public class Dept {
	private String deptNo;
	private String deptName;
	public Dept() {
		super();
	}
	public String getDeptNo() {
		return deptNo;
	}
	public void setDeptNo(String deptNo) {
		this.deptNo = deptNo;
	}
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	
	public String toString()
	{
		return " deptNo is: "+deptNo+" deptName is: "+deptName;
	}
}

 3.修改User.java

    在User类中添加对象Dept dept;

 4 修改User.xml

<?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="User">
	<resultMap type="User" id="userResult">
		<id property="id" column="user_id" />
		<result property="userName" column="user_name" />
		<association property="dept" column="user_dept_no"
			javaType="Dept">
			<id property="deptNo" column="dept_no" />
			<result property="deptName" column="dept_name" />
		</association>
	</resultMap>
	<select id="select1" parameterType="int" resultMap="userResult">
		select u.id
		as user_id,
		u.username as user_name,
		u.deptno as user_dept_no,
		d.deptno
		as dept_no,
		d.deptname as dept_name
		from t_user u,t_dept d
		where u.deptno
		= d.deptno
		and u.id = #{id}
    </select>
</mapper>

 上述配置文件中resultMap中使用了<association>标签来实现关联。

5.在UserDAO类中加入以下方法:

public User getUserAndDept(int id)
	{
		SqlSession session = sqlSessionFactory.openSession();
		try {
			User user = (User) session.selectOne("User.select1", id);
			return user;
		} finally {
			session.close();
		}
	}

 6.在test中进行测试。

 

 
相关标签: mybatis