简体   繁体   中英

How to filter a @OneToMany mapped field in spring data JPA?

I am trying to build an expense tracker application using Spring Boot REST api. The following are the entity classes I have created.

User Model

@Entity
public class User{
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    @NotBlank(message = "username is required !")
    @Column(unique = true)
    @Size(min = 10,max = 10,message = "username must be exactly 10 characters in length !")
    private String username;
    
    @Email(message = "Must be a valid Email !")
    @NotBlank(message = "Email is required !")
    @Size(min = 5, max = 256, message = "Email must be between 5 and 256 characters in length !")
    private String email;
    
    @NotBlank(message = "Password is required !")
    @Size(min = 8 , message = "Password must be greater than 8 characters in length !")
    private String password;
    
    @NotBlank(message = "FirstName is required !")
    @Size(min = 3 , max = 100 , message = "FirstName must be between 3 and 100 characters in length !")
    private String firstName;
    
    @NotBlank(message = "LastName is required !")
    @Size(min = 3 , max = 100 , message = "LastName must be between 3 and 100 characters in length !")
    private String lastName;
    
    @OneToOne(cascade = CascadeType.ALL)
    private Balance balance;
    
    @OrderBy("createdAt DESC")
    @OneToMany(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
    private List<Expense> expensesList;
    
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
   ......
}

Expense Model

@Entity
@Table(name = "expense_tracker_expenses")
public class Expense {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    @ManyToOne(fetch = FetchType.LAZY)
    private User user;
    
    @NotBlank(message = "Title is required !")
    @Size(min = 3 , max = 60 , message = "Title must be between 3 and 8 characters !")
    private String title;
    
    @Size(max = 256, message = "Note must be less than 256 characters !")
    private String note;
    
    @DecimalMin(value = "0.0",message = "Amount cannot be less than 0.0 !")
    private double amount;
    
    @NotBlank(message = "Category is required !")
    @Pattern(regexp = "Clothing|Entertainment|Food|Fuel|Health|Salary|Misc", message = "Invalid category !")
    private String category;
    
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
 ...
}

I created a method

public List<Expense> findByCreatedAtBetween(Date startCreatedAt,Date endCreatedAt);

to fetch the list of expenses between the dates but it returns the expenses of all users between the dates.

How to get the list of expenses of a certain user between a start date and an end date?

There are 2 ways to do

  1. Using JPA to query using AND predicate.
public List<Expense> findByUserAndCreatedAtBetween(User user,
                                                   Date startCreatedAt,
                                                   Date endCreatedAt);
  1. Filtering in Java after fetching all the expenses of the user.
user.getExpensesList().stream().filter(item -> 
    item.getCreatedAt().after(startDate) && 
    item.getCreatedAt().before(endDate)
).collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM