我有两个实体
@Entity
@Table(name = "steps")
public class Step {
@Id
@Column(nullable = false, insertable = true, updatable = true)
private long id;
//more fields
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "result_id", referencedColumnName = "id")
private Result result;
和
@Entity
@Table(name = "results")
public class Result {
@Id
@Column(nullable = false, insertable = true, updatable = true)
private long id;
//more fields
@OneToMany(mappedBy = "result", fetch = FetchType.EAGER)
private List<Step> steps;
现在我需要获得所有结果及其相关步骤
我会想要所有的步骤,所以一个急切的提取似乎是最好的,我知道所有的结果将有步骤,所以内部连接将没有问题。
我想从结果中得到更多的字段,但不是全部,所以我可以最大限度地使用索引,因此需要投影。
为此,我尝试了两种方法:
Query query = getSession().createQuery(
"select distinct result from Result as result " +
"inner join result.steps " +
"where result.monitorId = :id " +
"and result.completed between :from and :to ");
query.setLong("id", monitorId);
query.setTimestamp("from", from);
query.setTimestamp("to", to);
for (Result result : query.list()) {
result.getSteps()
//work work
}
Hibernate按照我的意愿进行连接,但是当我开始迭代结果时,Hibernate会在我正在使用的每个步骤中再记录一个选择查询。 (如果我要走这条路线,我也没有找到一个很好的投影方式?)
到目前为止,我尝试的第二种方法看起来很棒:
Criteria criteria = getSession().createCriteria(Result.class);
criteria.setProjection(Projections.projectionList()
.add(Projections.property("completed"), "completed")
.add(Projections.property("steps"), "steps"));
criteria.add(Restrictions.eq("someId", someId));
criteria.add(Restrictions.between("completed", from, to));
criteria.setFetchMode("steps", FetchMode.JOIN);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setResultTransformer(Transformers.aliasToBean(Result.class));
只要我不包括步骤,预测就会很好。我猜这与它不属于实际的数据库表有什么关系?当我尝试步骤时,我会
java.lang.ArrayIndexOutOfBoundsException: 2
on criteria.list();
所以我的主要问题是,我如何最好地对结果中的一些但不是所有列进行热切提取+一系列属于每个结果的步骤? 请帮忙? :)