JPA return from the Many side of an entity @OneToMany using @OrderBy

4

I have the following Cliente entity that has Pedidos .

The relationship between clients and requests is mapped with Cliente @OneToMany and Pedidos @ManyToOne . What I need is for the Customer Requests list to be sorted by Pedido.id .

After some research I discovered that I should use @OrderBy , the problem is that I'm not sure how to use it. Here is the code:

@Entity
@Table
public class Cliente implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @Email
    @NotEmpty
    private String email;

    @OneToMany(mappedBy ="cliente",cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    @OrderBy("cliente.Pedido.id ASC")
    private List<Pedido> pedidos;


@Entity
@Table
public class Pedido implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_pedido")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Cliente cliente;

Given this, how should my @OrderBy annotation be so that when I pull out the clients, the requests are sorted by id ?

Here is the code for how to query the data:

public class ClientePU implements Serializable{
    @Inject
    private EntityManager manager;

    public Cliente clientePorEmail(String email){
        return manager.find(Cliente.class, email);
    }

    public void salvarNovoCliente(Cliente cliente){
        manager.merge(cliente);
    }
}

When querying clients, the framework already returns me the list of Customers with the proper joins in Orders ...

    
asked by anonymous 15.08.2018 / 15:30

1 answer

4

If I were you, I'd give up @OrderBy because it would be applied to requests for any queries from the Client entity. I recommend using JPQL to do this query:

public Cliente clientePorEmail(String email) {
    Query query = manager.createQuery("SELECT cliente FROM Cliente cliente
        JOIN cliente.pedidos pedido 
        WHERE cliente.email = :email ORDER BY pedido.id");
    query.setParameter("email", email);
    return (Cliente) query.getSingleResult();
}

If you really want to use the annotation, you can use it as follows if the goal is to sort by Order ID:

@OrderBy("id ASC")
List <Pedido> pedidos;
    
15.08.2018 / 15:50