Hibernate Criteria按示例映射查询

时间:2013-06-18 11:38:59

标签: hibernate hibernate-mapping

此信封只映射了一个Envelope对象和2个Invoice对象。当我尝试使用以下代码进行查询时,它返回2个相同的Envelope对象。我认为我的hibernate注释存在问题。有什么解决方案吗?

Envelope envelope = new Envelope();
envelope.setPostBox(EnvelopePostBox.INBOX.name());        
List<Envelope> byTemplate = genericDao.getByTemplate(envelope);

信封实体;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "envelope", fetch = FetchType.EAGER)
private List<Invoice> invoiceList;

发票实体;

@JoinColumn(name = "envelope", referencedColumnName = "instance_identifier")
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Envelope envelope;  

我的道法;

@Transactional(readOnly = true)
public <T> List<T> getByTemplate(T templateEntity) {
    Criteria criteria = getCurrentSession().createCriteria(templateEntity.getClass());
    criteria.add(Example.create(templateEntity));
    return criteria.list();
}

1 个答案:

答案 0 :(得分:0)

尝试以下代码,

@Transactional(readOnly = true)
public <T> List<T> getByTemplate(T templateEntity) {
    Criteria criteria = getCurrentSession().createCriteria(templateEntity.getClass());
    criteria.add(Example.create(templateEntity));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return criteria.list();
}