使用MyBatis的resultMap高级查询时常用的方式总结

以下内容已经通过楼主测试, 从pd设计数据库到测试完成, 之前楼主也没有过Mybatis 使用resultMap觉得有点乱,最近抽出时间总结了一下也算对MyBatis的resultMap进行一次系统的学习, 希望与大家分享学习心得, 有说的不对的地方请大家帮指教

下面是PD设计的几张数据库模型

先说下表吧 多对多 采用 传统而经典的 用户角色表,并没有采用当今流行的联合主键方式 而是将 用户表_id 和 角色表_id 进行Unique

详情参见http://www.cnblogs.com/YingYue/p/3983611.html

,   单项一对多采用 班级学生表 (一个班级有多个学生, 一个学生只能在一个班级, 大学除外否则就是多对多了, 哈哈)

Mybatis的resultMap操作多表的方式 大致如下几种方式

  方式一: 在resultMap中指定其他表的列名用column指向其他表的column同时在当前表对应的实体类中添加一个标识字段

 

<?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="UserMapper" >
  <resultMap id="BaseResultMap" type="entity.User" >
    <id column="ID" property="id" jdbcType="VARCHAR" />
    <result column="USER_NAME" property="userName" jdbcType="VARCHAR" />
    <result column="PASSWORD" property="password" jdbcType="VARCHAR" />
    
  <!-- USER_ID这个列USER表中并不存在, 这个列存在于USER_ROLE中 通过flag指向USER_ROLE的USER_ID列 -->
  <result column="USER_ID" property="flag" jdbcType="VARCHAR" /> </resultMap> <!-- 查询用户带有的角色 --> <select id="selectUserOfRole" resultMap="BaseResultMap" parameterType="java.lang.String" > select * from user u left join user_role ur on u.id = ur.user_id <if test="id != null"> where ID = #{id,jdbcType=VARCHAR} </if> <if test="userName != null"> where USER_NAME = #{userName,jdbcType=VARCHAR} </if> </select> </mapper>

java

package entity;

public class User {
    private String id;

    private String userName;

    private String password;
    //这个就是在标示字段, 数据库中并不存在, 而是通过 USER_ID 指向 USER_ROLE的USER_ID列
    private String flag;
    
    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } }

方式二:

 

转载于:https://www.cnblogs.com/YingYue/p/3984259.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值