您的位置:首页 > 其它

mybatis是开发项目的重点,很多人在写一对多经常出问题,下面我为大家提供一个模板

2020-01-01 15:40 169 查看
准备表
create table t_employee(
eid int PRIMARY KEY auto_increment,
ename varchar(50),
epassword varchar(50),
eage int,
ebirthday Date,
dept_id int,
FOREIGN KEY (dept_id) REFERENCES t_department(did)
)
create table t_department(
did int primary KEY auto_increment,
dname varchar(50),
dlocation varchar(50)
)
### 多对一
>`<?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.model.mapper.EmployeeMapper">
<resultMap id="empResultMap" type="employee">
<id property="eid" column="eid"/>
<result property="ename" column="ename"/>
<result property="epassword" column="epassword"/>
<result property="eage" column="eage"/>
<result property="ebirthday" column="ebirthday"/>
<association property="department" javaType="department">
<id property="did" column="did"/>
<result property="dname" column="dname"/>
<result property="dlocation" column="dlocation"/>
</association>
</resultMap>
<select id="get" resultMap="empResultMap">
select eid,ename,eage,epassword,ebirthday,dept_id
from t_employee
where dept_id=#{did}
</select>
<select id="findEmployees" resultMap="empResultMap">
select e.eid,e.ename,e.epassword,e.eage,e.ebirthday,d.did,d.dname,d.dlocation
from t_employee e inner join t_department d
on  e.dept_id=d.did
</select>
</mapper>
## 一对多
<?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.model.mapper.DepartmentMapper">
<resultMap id="deptResultMap" type="department">
<id property="did" column="did"/>
<result property="dname" column="dname"/>
<result property="dlocation" column="dlocation"/><!--下面的是一对多的关联查询 使用的懒加载 ofType表示的是关联数据的类型,column是把本department的主键传入多表的
的get的方法,作为该方法的查询参数,重点,别整反了 ,需要中点注意 -->
<collection property="empolyees" ofType="employee" column="did"
select="com.model.mapper.EmployeeMapper.get"/>
</resultMap>
<select id="findAllDept" resultMap="deptResultMap" useCache="true">
select did,dname,dlocation
from t_department
</select>
</mapper>

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐