gpt4 book ai didi

java - OneToMany 关系的 Spring Data JPA 规范

转载 作者:太空宇宙 更新时间:2023-11-04 12:17:06 27 4
gpt4 key购买 nike

我在使用 Spring data JPA 规范获取列表实体类别时遇到问题。我需要获取所有类别及其食谱,其中 Recipe.dateModified大于某个日期。我不知道如何创建我的谓词来填充 Collection<Recipe>在每个类别中,只有那些大于此日期的食谱。

@Entity    
public class Category {

private int id;
private String name;

@OneToMany(mappedBy = "categories")
private Collection<Recipe> recipes;
}

@Entity
public class Recipe {

private int id;
private String name;

private Timestamp dateModified;

}

CategoryService我得到List<Category>使用规范:

@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);
};
}

}

最佳答案

在您的 CategoryRepository 实现类中,添加此方法

public Category findAll(Date dateModified) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Category> query = builder.createQuery(Category.class);
Root<Category> category = query.from(Category.class);

ParameterExpression<Date> dateParam = builder.parameter(Date.class);
query.select(category).where(builder.greaterThan(category.get(Category_.recipes).get(Recipe_.dateModified), dateParam));

return em.createQuery(query)
.setParameter(dateParam, dateModified)
.getSingleResult();
}

上面的代码中使用了 MetaModel 类。如果没有生成元模型类,请在 pom 文件中添加此插件以自动生成元模型类..

<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<version>2.2.4</version>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>5.2.2.Final</version>
</dependency>
</dependencies>
</plugin>

关于java - OneToMany 关系的 Spring Data JPA 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39272610/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com