我有三个实体User,Center和Profile,因此用户根据他所在的中心有不同的配置文件。所以我们有一个表连接称为* user_center_profile *的三个实体。
然后我们有另一个实体,称为Permission,它链接到Profile,因此一个配置文件有多个权限。
因为主要实体是用户,所以我把它像这样:
@Entity
@Table(name = "profile")
public class Profile implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idprofile")
private Long idProfile;
@Column(name = "codprofile")
private String codProfile;
@Column(name = "desprofile")
private String desProfile;
@OneToMany
@JoinTable(name = "profile_permission", joinColumns = { @JoinColumn(name = "idProfile") }, inverseJoinColumns = { @JoinColumn(name = "idPermission") })
private List<Permission> permissions = new ArrayList<Permission>();
/* getters and setters */
}
@Entity
@IdClass(CenterProfileId.class)
@Table(name = "user_center_profile")
public class CenterProfile implements Serializable {
@Id
@ManyToOne
private Center center;
@Id
@ManyToOne
private Profile profile;
/* getters and setters */
}
@Embeddable
public class CenterProfileId implements Serializable {
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name = "idCenter")
private Center center;
@ManyToOne
@JoinColumn(name = "idProfile")
private Profile profile;
/* getters, setters, equals, hashcode */
}
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idUser")
private Long idUser;
@Column(name = "codUser")
private String codUser;
/* other properties */
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_center_profile", joinColumns = { @JoinColumn(name = "idUser") }, inverseJoinColumns = {
@JoinColumn(name = "idCenter"), @JoinColumn(name = "idProfile") })
private List<CenterProfile> centersProfileUser = new ArrayList<CenterProfile>();
@Transient
private Center selectedCenter;
/* getters, setters */
}
事情是,在某些时候我必须收集某个用户拥有的所有权限...我尝试了几件事,我得到了延迟加载错误,没有会话或会话关闭错误,加载同步包的问题......
我甚至尝试编写一个简单的SQL查询,但我得到了同样的错误......
我无法看到为此构建DetachedCriteria的方法,我不知道它是否也会给出异常..
我的应用可以连接到不同的“中心”,当他登录时,他可以选择他想要连接的中心,但是一旦登录,他就可以改变中心...所以当他改变它时,我必须重新计算他的权限......这就是我需要获得权限列表的原因..
我怎样才能以正确的方式完成这项工作?
答案 0 :(得分:0)
最后,我构建了这样的查询:
HashSet<Permission> set = new HashSet<Permission>();
for (CenterProfile cp : usuario.getCentersProfileUsuario()) {
// First we build subcriteria to return all the permissions for a certain profile
DetachedCriteria criteriaProfile = DetachedCriteria
.forClass(Profile.class);
criteriaProfile.add(Restrictions.eq("idProfile", cp.getProfile()
.getIdProfile()));
criteriaProfile.createAlias("permissions", "permission");
criteriaProfile.setProjection(Property.forName("permission.idPermission"));
// Then we build criteria for permissions, which should match the results given by subcriteria
DetachedCriteria criteria = DetachedCriteria
.forClass(Permission.class);
criteria.add(Property.forName("idPermission").in(criteriaProfile));
List<Permission> permissions = getHibernateTemplate().findByCriteria(
criteria);
set.addAll(permissions);
}