V
V
Vitaly2016-09-16 17:30:13
Java
Vitaly, 2016-09-16 17:30:13

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();

}

In CategoryService I get List using Specification:
@Service   
public class CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    public List<Category> findAll(Date date) {
        return categoryRepository.findAll(where(byDateModified(date)));
    }

}

I tried to use this Specification, but it doesn't work:
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

1 answer(s)
A
aol-nnov, 2016-09-16
@aol-nnov

haven't used this black magic yet, but what about
findAllByRecipesDateModifiedGreaterThan(Date date)? %)
docs.spring.io/spring-data/jpa/docs/current/refere...
be sure to tell us what happened! )) is interesting )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question