实体类
User
private Integer id; // 主键
private Date birthday; // 生日
private String gender; // 性别
private String username; // 用户名,唯一
private String password; // 密码
private String remark; // 备注
private String station; // 状态
private String telephone; // 联系电话
private Set<Role> roles = new HashSet<Role>(0);//对应角色集合
Role
private Integer id;
private String name; // 角色名称
private String keyword; // 角色关键字,用于权限控制
private String description; // 描述
private Set<User> users = new HashSet<User>(0);
private Set<Permission> permissions = new HashSet<Permission>(0);
private LinkedHashSet<Menu> menus = new LinkedHashSet<Menu>(0);
Permission
private Integer id;
private String name; // 权限名称
private String keyword; // 权限关键字,用于权限控制
private String description; // 描述
private Set<Role> roles = new HashSet<Role>(0);
mapper.xml文件
UserMapper.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="com.gzy.dao.UserDao">
<resultMap id="baseUserResultMap" type="com.gzy.health.pojo.User">
<id column="id" property="id"/>
</resultMap>
<resultMap id="userResultMap" type="com.gzy.health.pojo.User" extends="baseUserResultMap">
<collection property="roles" javaType="set" ofType="com.gzy.health.pojo.Role"
column="user_id=id" select="com.gzy.dao.RoleDao.getRoleByUserId"></collection>
</resultMap>
<select id="getUserByName" resultMap="userResultMap">
select * from t_user where username=#{username}
</select>
</mapper>
RoleMapper.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="com.gzy.dao.RoleDao">
<resultMap id="baseRoleResultMap" type="com.gzy.health.pojo.Role">
<id property="id" column="id"/>
</resultMap>
<resultMap id="roleResultMap" type="com.gzy.health.pojo.Role" extends="baseRoleResultMap">
<collection property="permissions" javaType="set"
ofType="com.gzy.health.pojo.Permission" column="role_id=id" select="com.gzy.dao.PermissionDao.getPermissionByRoleId"/>
</resultMap>
<select id="getRoleByUserId" resultMap="roleResultMap">
SELECT * FROM t_role WHERE id IN(SELECT role_id FROM t_user_role WHERE user_id=#{user_id})
</select>
</mapper>
PermissionMapper.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="com.gzy.dao.PermissionDao">
<select id="getPermissionByRoleId" resultType="Permission">
SELECT * FROM t_permission WHERE id IN(SELECT permission_id
FROM t_role_permission WHERE role_id=#{role_id})
</select>
</mapper>
我在开发遇到的问题是<collection >中的 javaTypee属性没有对应SET集合类型对应的别名,然后翻底层发现,mybatis根本没有提供SET集合的别名。所以需要自己注册别名。
注册很简单只要在mybatis配置文件中添加:
<typeAliases>
<typeAlias alias="set" type="java.util.Set"/>
</typeAliases>
这样就可以解决问题了。
网友评论