Answer the question
In order to leave comments, you need to log in
How to populate List by Spring Data JPA Specification for OneToMany Relationship?
I have a problem getting a list of Category entities using Spring data JPA specifications. I need to get all categories with their Recipes where Recipe.dateModified is greater than some date. I do not know how to create my own Predicate that would fill the Collection in each category with only those recipes whose dateModified is greater than some date.
@Entity
public class Category {
private int id;
private String name;
@OneToMany(mappedBy = "category")
private Collection<Recipe> recipes;
}
@Entity
public class Recipe {
private int id;
private String name;
@ManyToOne
@JoinColumn(name = "category_id", referencedColumnName = "id")
private Category category;
@Temporal(TemporalType.TIMESTAMP)
private Date dateModified = new Date();
}
@Service
public class CategoryService {
@Autowired
private CategoryRepository categoryRepository;
public List<Category> findAll(Date date) {
return categoryRepository.findAll(where(byDateModified(date)));
}
}
public class RecipeSpec {
public static Specification<Category> byDateModified(Date date) {
return (root, query, builder) -> {
final Join<Category, Recipe> recipe = root.join(Category_.recipes, JoinType.LEFT);
return builder.greaterThan(recipe.get(Recipe_.dateModified), date);
};
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question