我正在尝试实现对所有A
类型的对象的简单HQL查询,这些对象按以下 predicate 排序:
a.getListB().get(0).getC().getLastname()
我尝试了以下HQL查询:
select a_ from A a_ order by a_.listB.c.lastname
但我得到了以下例外:
org.hibernate.QueryException: illegal attempt to dereference collection
我尝试了以下SQL查询,但得到的结果不一致:
select a.* from A a
left outer join B b on b.a_id=a.id
left outer join C c on b.uploaded_from=c.id
order by c.lastname=(select c_.lastname from A a_
left outer join B b_ on b_.a_id=a_.id
left outer join C c_ on b_.uploaded_from=c_.id
where a.id=a_.id limit 1) asc;
代码片段:
@Entity
@Table(name = "A")
pubic class A {
private int id;
private List<B> listB;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
@OrderBy(clause = "id")
@OneToMany(fetch = FetchType.LAZY, mappedBy = "a")
public List<B> getListB() {
return this.listB;
}
}
@Entity
@Table(name = "B")
pubic class B {
private int id;
private A a;
private C c;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id", nullable = false)
public A getA() {
return this.a;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "uploaded_from", nullable = false)
public C getC() {
return this.c;
}
}
@Entity
@Table(name = "C")
pubic class C {
private int id;
private String lastname;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
@Column(name = "lastname")
public String getLastname() {
return this.lastname;
}
}
有什么提示我可以用HQL、Criteria甚至是原生SQL来解决这个问题吗?
1条答案
按热度按时间gkn4icbw1#
我使用下面的表格测试了下面针对您的问题的一种可能的解决方案
唯一的id_a条目通过此中间选择进行编号:
结果:
通过仅选择rowNumber=1的条目,我们现在只能获得与A条目关联的第一个C条目:
结果:
通过加入C语言,现在可以按姓氏进行排序:
结果:
(使用Postgres 14.3进行测试)