首先 數據庫結構如下
如上,一共五張表 用戶表、角色表、菜單表、 用戶角色表、菜單角色表;
這裏只說其中的用戶表、用戶角色表,角色表
一對多關係表現在一個用戶可以具有多個角色,根據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>