用户sys_userinfo和角色sys_role,典型的多对多关系,
用户表:sys_userinfo
角色表:sys_role
关联表:rel_user_role
用户sysUserInfo:
@Entity
@Table(name = "SYS_USERINFO")
public class SysUserinfo implements java.io.Serializable
{
private static final long serialVersionUID = 4562586475125905669L;
private Integer userId;
private String loginPhone;
private String password;
private String userName; // 姓名
private byte sex = 0;
private boolean isActive;
private boolean enabled;
private String receiveNum; // 短信接收号码
private int score;
private String homePhone; // 家庭电话
private String linkPhone; // 联系电话
private String email;
private String disableReason;// 禁用原因
private Date createTime;
private Date updateTime;
private String createBy;
private String updateBy;
private SysRole role; // 用户当前角色
private boolean deleted = false; // 已被删除
private Set<SysArea> areas = new HashSet<SysArea>(0); // 用户区域
private Set<SysRole> roles = new HashSet<SysRole>(0); // 用户所有角色
private EduSchool school; // 用户所属的学校
private String clientAppId;
private String openId; // 微信公众账号openId
自增长主键:
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "USER_ID")
public Integer getUserId()
{
return this.userId;
}
public void setUserId(Integer userId)
{
this.userId = userId;
}
用户与角色的多对多注解,采用的是懒加载,中间表为name="REL_USER_ROLE",后面JoinColumn依次是本表用户id,关联表角色id(joinColumns后面是本类表的主键,inverseJoinColumns后面是关联类表的主键,joinColumns和inverseJoinColumns加s是因为复合主键的存在,不常用)
如果是双向的话,在sysRoles端直接定义@ManyToMany(mappedBy="sysUserInfo")即可
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST })
@JoinTable(name = "REL_USER_ROLE", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
@NotFound(action = NotFoundAction.IGNORE)
public Set<SysRole> getRoles()
{
return roles;
}
public void setRoles(Set<SysRole> roles)
{
this.roles = roles;
}
其他get,set方法省略
角色sysRole
@Entity
@Table(name = "SYS_ROLE")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class SysRole implements java.io.Serializable,Comparable<SysRole>
{
private static final long serialVersionUID = 7791075888623020580L;
private Integer roleId;
private String roleName;
private char roleType;
private String aliasName;
private byte roleLevel;
private List<SysFunction> functions = new ArrayList<SysFunction>(0);
只在一方加入@ManyToMany即可实现,根据用户查所拥有的角色,根据角色查拥有该角色的用户信息
DAO查询代码:
/**
* 根据角色id查询用户id
* @param objectType
* @return
*/
public List<SysUserinfo> secletUserInfos(int objectType){
DetachedCriteria criteria = DetachedCriteria.forClass(SysUserinfo.class);
criteria.createAlias("roles", "r");
criteria.add(Restrictions.eq("r.roleId",objectType));
return getHibernateTemplate().findByCriteria(criteria);
}
而根据用户id查角色更简单,查询用户信息javabean,直接get即可