gpt4 book ai didi

JPA CRITERIA QUERY,按连接列排序

转载 作者:行者123 更新时间:2023-12-04 23:16:18 25 4
gpt4 key购买 nike

如何在加入的实体上调用 order by?我正在尝试通过以下方式实现以下目标:

select * from person p inner join telephone t on p.id=t.person_id join sim s on s.id=t.sim_id order by s.name DESC

@Entity
public class Person implements Serializable{
@Id
private Long id;
@OneToMany(orphanRemoval = true, mappedBy = "person", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private List<Telephone> telephonesNumber;

@Entity
public class Telephone implements Serializable {
@Id
private String number;
@Id
@ManyToOne()
@JoinColumn(name = "person_id")
private Person person;
@Id
@ManyToOne(cascade = {})
@JoinColumn(name = "sim_id")
private Sim sim;

@Entity
public class Sim implements Serializable {
@Id
private Long id;
@Column(unique = true)
private String name;

我使用规范接口(interface),在这个例子中排序是在字段 person.id 上,它可以工作
public class PersonSpecification implements Specification<Person> {

@Override
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
List<Predicate> predicates = new ArrayList<>();
// there is many different conditions for example
// if(someCondition!=null) {
// predicates.add(builder.like(root.get("someProperty"), someValue));
// }


query.groupBy(root.get("id"));
//there I want to order by Sim.name i dont know how
query.orderBy(builder.asc(root.get("phone")));//this works
return builder.and((predicates.toArray(new Predicate[predicates.size()])));
}

我想按 Sim.name 订购,但我不知道如何。

最佳答案

在 JPA 规范中,您可以使用:

query.orderBy(builder.asc(root.join("telephonesNumber").get("sim").get("name")));

按sim名称排序。

更多细节:
https://en.wikibooks.org/wiki/Java_Persistence/Querying#Joining.2C_querying_on_a_OneToMany_relationship

如果您使用 JPA 查询:
@Query("select s from Person p 
join p.telephonesNumber t
join t.sim s order
by t.sim.id desc")

它会产生这个:
select * from person p 
inner join telephone t on p.id=t.person_id
inner join sim s on t.sim_id=s.id
order by t.sim_id desc

更多细节:

https://github.com/abhilekhsingh041992/spring-boot-samples/blob/master/jpa/src/main/java/example/springboot/jpa/repository/PersonRepository.java

关于JPA CRITERIA QUERY,按连接列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41192305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com