zl程序教程

您现在的位置是:首页 >  后端

当前栏目

mybatisplus关联表查询_hibernate多表查询

hibernate 查询 关联 多表 MyBatisPlus
2023-06-13 09:13:45 时间

大家好,又见面了,我是你们的朋友全栈君。

我们在设计表的时候往往一个表的外键作为另一张表的主键,那么我们在查询的时候就要查询两个表的数据。

下面来说下实现的方法。

数据库表的结构

wc_user实体类


public class WcUser implements Serializable {
	//用户id
    private String userId;
    //用户密码
    private String userPassword;
    //是否被锁定,0锁定,1没锁
    private String userActive;

wc_user_roles实体类

public class WcUserRoles implements Serializable {
	//用户id
    private String userId;
    //用户角色
    private String userRole;

由于要连表查询所以我们还要创建一个表,只有把另一个类添加进来就好了。

public class WcUserAll {
    private String userId;

    private String userPassword;

    private String userActive;
    
    private WcUserRoles wcUserRoles;

	public WcUserAll(String userId, String userPassword, String userActive) {
		super();
		this.userId = userId;
		this.userPassword = userPassword;
		this.userActive = userActive;
	}

在WcUserMapper.xml写一个WcUserAll类的resultMap,然后使用左外连接(left join)就可以实现连表查询了

	<resultMap id="WithRoleResultMap" type="com.smxy.wechat.pojo.WcUserAll">
		<id column="user_id" property="userId" jdbcType="VARCHAR" />
		<result column="user_password" property="userPassword"
			jdbcType="VARCHAR" />
		<result column="user_active" property="userActive" jdbcType="VARCHAR" />
		<association property="wcUserRoles" javaType="com.smxy.wechat.pojo.WcUserRoles">
			<id column="user_id" property="userId" jdbcType="VARCHAR" />
			<result column="user_role" property="userRole" jdbcType="VARCHAR" />
		</association>
	</resultMap>
	<select id="selectRoleByPrimaryKey" resultMap="WithRoleResultMap"
		parameterType="java.lang.String">
		select
		<include refid="withRole_Column_List" />
		from wc_user a
		left join
		wc_user_roles b on a.`user_id`=b.`user_id`
		where a.user_id=#{userId,jdbcType=VARCHAR}
	</select>

在Controller调用selectRoleByPrimaryKey该方法就可以查询了

查询结果如下图

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。