pepe
pepe

Reputation: 335

How to use an order by clause with an embedded field in the spring data jpa derived query?

I have two entities : Article and Category

@AllArgsConstructor
@Entity
@ToString
@Table(name = "articles")
public class Article {
        
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "id")
   private Long id;
        
   @Column(name = "title", nullable = false, unique = true)
   private String title;
    
   @Embedded
   private Audit audit = new Audit();
        
   @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE})
   @JoinTable(name = "articles_categories", joinColumns = {@JoinColumn(name = "articles_id")}, inverseJoinColumns = {@JoinColumn(name = "categories_id")})
   @JsonManagedReference
   private List<Category> categories = new ArrayList<>();

Now the entity Category Then I have Category entity

@Getter
@Setter
@Accessors ( chain = true )
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table ( name = "category" )
public class Category {
   
  @Id
  @GeneratedValue ( strategy = GenerationType.IDENTITY )
  @Column ( name = "id" )
  private Long id;
    
  @Column ( name = "name", nullable = false, unique = true )
  private String name;
    
  @ManyToMany ( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST , CascadeType.MERGE }, mappedBy = "categories" )
  @JsonBackReference
  private Set<Article> categories = new HashSet<>();
}

And now the entity Embedded

@Getter
@Setter
@Embeddable
@RequiredArgsConstructor
public class Audit {
    
   @Column ( name = "created_on" )
   private Date createdOn;
    
   @Column ( name = "updated_on" )
   private Date updatedOn;
    
   @PrePersist
   public void prePersist ( ) {
      createdOn = new Date ( );
   }
    
   @PreUpdate
   public void preUpdate ( ) {
       updatedOn = new Date ( );
   }
}

In my article repository I have the following JPA.

@Repository
public interface ArticleRepository extends JpaRepository < Article, Long > { 
        
   Page<Article> findByCategoriesIn (List<Category> categories, Pageable pageable);

}

This works correctly and is returning a page of articles but I would like to order articles by creation date using @Embeeded annotation.

How could I use this ?

Upvotes: 1

Views: 558

Answers (1)

SternK
SternK

Reputation: 13041

Try to use something like this:

Page<Article> findByCategoriesInOrderByAudit_CreatedOnDesc(List<Category> categories, Pageable pageable);

See also this and this sections of the documentation.

Upvotes: 1

Related Questions