SSM笔记:mybatis/mybatis-plus 一对多通过xml配置实现

首先 数据库结构如下

如上,一共五张表 用户表、角色表、菜单表、 用户角色表、菜单角色表;

这里只说其中的用户表用户角色表角色表 

一对多关系表现在一个用户可以具有多个角色,根据SSM框架分层,使用generator插件生成对应的实体和dao层接口,保证数据库字段名与实体字段名保持一致;

得到如下结构:

实体:不提供详细代码,因为字段和数据库字段一致,由于一对多,用户类需要增加一个字段:   

 private List<Role> roles;

还需要注意的是:

      mybatis-plus要求在User类上添加表名注解;

      关联xml中的resultMapper;

User类代码:

@TableName(value = "user", resultMap = "userMap")
public class User implements UserDetails {

//...省略其他字段

 @Getter
 @Setter
 private List<Role> roles;
}

对应dao层接口mapper(继承自mybatis-plus,基本接口不用再写):

public interface UserMapper extends BaseMapper<User> {
}

dao层接口对应xml配置文件:

<?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="org.weipiru.server1.mapper.UserMapper">
    <resultMap id="userMap" type="org.weipiru.server1.beans.User">
        <id column="uid" property="uid"/>
       <!--猜测:column 会传入子查询-->
        <collection property="roles" ofType="org.weipiru.server1.beans.Role" column="uid" select="findRolesByUid"/>
    </resultMap>

  <select id="findRolesByUid" resultType="org.weipiru.server1.beans.Role">
        select t_relate.role_id,t_relate.user_id,role.*
        from user_role as t_relate
                 right join role on t_relate.role_id = role.uid
        where t_relate.user_id = #{uid}
    </select>
</mapper>

 

发布了26 篇原创文章 · 获赞 10 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章