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

准备表
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>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值