CoderYuanX 2024-08-15 17:15 采纳率: 14.3%
浏览 5

关于#java#的问题:Mybaits里一对多的 带条件的查询怎么处理啊

Mybaits里一对多的 带条件的查询怎么处理啊?
分别有三张表user表,role表 和user_role表 通过userId和roleId进行关联,
一个用户有可能有多个角色,现在有个需求是要对用户表进行分页查询查询,而且需要每条数据带上他的角色名称,比如 张三 经理,CEO 而且 角色可以作为查询条件传进去,比如我想查询角色是CEO的用户有哪些,
怎么在java代码和sql上进行操作

  • 写回答

2条回答 默认 最新

  • 一直免费一直爽 2024-08-15 17:16
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    在MyBatis中,可以使用<resultMap>标签来处理一对多的查询。首先,需要在mapper.xml文件中定义一个<resultMap>,用于描述如何从数据库表中获取数据并将其映射到Java对象。然后,在<select>标签中使用这个<resultMap>来进行查询。

    假设你的表结构如下:

    user表:

    • id (用户ID)
    • name (用户名)

    role表:

    • id (角色ID)
    • name (角色名)

    user_role表:

    • user_id (用户ID)
    • role_id (角色ID)

    首先,创建一个User类和一个Role类:

    public class User {
        private int id;
        private String name;
        private List<Role> roles;
        // getter和setter方法
    }
    
    public class Role {
        private int id;
        private String name;
        // getter和setter方法
    }
    

    接下来,在mapper.xml文件中定义一个<resultMap>

    <resultMap id="UserWithRolesResultMap" type="User">
        <id property="id" column="user_id"/>
        <result property="name" column="user_name"/>
        <collection property="roles" ofType="Role">
            <id property="id" column="role_id"/>
            <result property="name" column="role_name"/>
        </collection>
    </resultMap>
    

    然后,编写一个带条件的查询语句:

    <select id="findUsersWithRolesByCondition" resultMap="UserWithRolesResultMap">
        SELECT u.id as user_id, u.name as user_name, r.id as role_id, r.name as role_name
        FROM user u
        LEFT JOIN user_role ur ON u.id = ur.user_id
        LEFT JOIN role r ON ur.role_id = r.id
        WHERE r.name = #{roleName}
    </select>
    

    最后,在你的Mapper接口中添加一个方法:

    public interface UserMapper {
        List<User> findUsersWithRolesByCondition(@Param("roleName") String roleName);
    }
    

    现在,你可以在Java代码中调用这个方法来查询具有特定角色的用户:

    List<User> users = userMapper.findUsersWithRolesByCondition("CEO");
    
    评论

报告相同问题?

问题事件

  • 创建了问题 8月15日