所以我一直在做这件事,而且似乎无法让它正常工作。
当我使用HibernateUtil.get(clazz, pkId)方法时,事情似乎工作正常,但是当我尝试使用HibernateUtil.pagedQuery(clazz, criteria, start, stop) 时,我得到了多个相同的对象返回。
例如,如果有 3 名员工分配给角色 1,那么运行...
Role role = HibernateUtil.get(Role.class, new Integer(1));
...按预期工作。但是,如果我跑...
List<Criterion> c = new ArrayList();
c.add(Restrictions.eq("roleTypeSeqNo", new Integer(1)));
List<Role> roles = (List<Role>) phi.util.hibernate.HibernateUtil.pagedQuery(Role.class, c, 0, 50);
... 返回一个包含 3 个相同角色的列表。所有这些都代表角色 1。
如果有人能引导我走上正确的道路,我将不胜感激。
提前致谢!
这是我的课程的缩写版本
@Entity
@Table(name="ASSIGNMENTS")
public class Assignment implements Serializable {
@EmbeddedId
private AssignmentPK pk;
// After coming across many errors I finally caved and reverted roleTypeSeqNo back to just an Integer.
private Integer roleTypeSeqNo;
private String status;
private String location;
}
@Embeddable
public class AssignmentPK implements Serializable {
@ManyToOne
@JoinColumn(name="EMPLID")
private Employee employee;
@Column(name="PRIORITY_NO")
private String priorityNo;
}
@Entity
public class Employee implements Serializable {
@Id
private Integer emplId;
private String name;
}
@Entity
public class Role implements Serializable {
@Id
private Integer roleTypeSeqNo;
private Integer reportsToRole;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="roleTypeSeqNo")
@JoinTable(
name="ASSIGNMENTS"
, joinColumns={@JoinColumn(name="ROLE_TYPE_SEQ_NO")}
, inverseJoinColumns={
@JoinColumn(name="EMPLID"),
@JoinColumn(name="PRIORITY_NO")
}
)
private List<Assignment> assignments;
}
public class HibernateUtil {
public static Object get(Class clazz, Serializable pkId) {
Session session = getSession();
Transaction transaction = session.beginTransaction();
Object obj = session.get(clazz, pkId);
transaction.commit();
session.close();
return obj;
}
public static List pagedQuery(Class clazz, List<Criterion> criterion, Integer start, Integer size){
Session session = getSession();
try {
Transaction transaction = session.beginTransaction();
DetachedCriteria dCriteria = DetachedCriteria.forClass(clazz);
for(Criterion c : criterion){
dCriteria.add(c);
}
dCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
dCriteria.setProjection(Projections.id());
Criteria criteria=session.createCriteria(clazz);
criteria.add(Subqueries.propertyIn("id", dCriteria));
criteria.setFirstResult(start);
criteria.setMaxResults(size);
List records = criteria.list();
transaction.commit();
return records;
} catch (Exception e) {
Logger.getLogger("HibernateUtil").log(Level.SEVERE, "There was an EXCEPTION THROWN!!!", e);
return null;
} finally {
session.close();
}
}
}