我有NetBeans生成的EJB外观,并且JPA提取的实体中的排序集合不起作用。这是代码:
@Stateless
public class CompetitionFacade extends AbstractFacade<Competition> implements CompetitionFacadeLocal {
@PersistenceContext(unitName = "mot_persistence_unit")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public CompetitionFacade() {
super(Competition.class);
}
@Override
public Competition findAndInitializeGD(Integer idCompetition) {
Competition entity = em.find(Competition.class, idCompetition);
entity.getGroupDetailsList().forEach(p -> System.out.println("First lambda " + p.getIdGroupName()));
new ArrayList<>(entity.getGroupDetailsList()).forEach(p -> System.out.println("Second lambda " + p.getIdGroupName()));
Collections.sort(entity.getGroupDetailsList(), new Comparator<GroupDetails>() {
@Override
public int compare(GroupDetails o1, GroupDetails o2) {
throw new UnsupportedOperationException("First sorting");
}
});
Collections.sort(new ArrayList<>(entity.getGroupDetailsList()), new Comparator<GroupDetails>() {
@Override
public int compare(GroupDetails o1, GroupDetails o2) {
throw new UnsupportedOperationException("Second sorting");
}
});
return entity;
}
}
AbstractFacade:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
// auto-generated methods like find/edit etc.
}
调用此方法会产生以下异常:
Caused by: java.lang.UnsupportedOperationException: Second sorting
为什么排序不会抛出第一个异常?看起来lambda表达式也不起作用。添加这两行后
entity.getGroupDetailsList().forEach(p -> System.out.println("First lambda " + p.getIdGroupName()));
new ArrayList<>(entity.getGroupDetailsList()).forEach(p -> System.out.println("Second lambda " + p.getIdGroupName()));
输出
Info: Second lambda entities.GroupName[ idGroupName=709 ]
Info: Second lambda entities.GroupName[ idGroupName=706 ]
Info: Second lambda entities.GroupName[ idGroupName=707 ]
Info: Second lambda entities.GroupName[ idGroupName=708 ]
编辑:
这是来自实体的字段
@OneToMany(cascade = CascadeType.ALL, mappedBy = "competition")
private List<GroupDetails> groupDetailsList = new ArrayList<>();
正常的吸气剂
public List<GroupDetails> getGroupDetailsList() {
return groupDetailsList;
}
EDIT2: 我在接受的答案之后找到了令人满意的答案https://stackoverflow.com/a/27980037/3803447,这正确地暗示了我。
答案 0 :(得分:0)
如果启用了延迟加载(这是默认设置),则getGroupDetailsList
返回的集合实际上是一个特殊的包装类,由JPA提供程序提供,用于在访问后为中间人提取数据集它。尝试调试并查看实际返回的类。