JPA CRITERIA QUERY按订单加入列

时间:2016-12-16 20:55:56

标签: jpa criteria-api

如何在已加入的实体上调用订单?我试图通过以下方式实现以下目标:

从p.id = t.person_id上的人员p内联接电话t中选择*通过s.name DESC在s.id = t.sim_id上加入sim s

@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;

我使用规范界面,在这个例子中,排序是在字段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订购,但我不知道如何。

1 个答案:

答案 0 :(得分:5)

在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