弹簧启动避免多次findBy



我需要在插入到featureEntity之前做一些检查:如果应用程序是活动的,如果它包含某个版本,如果某个版本有某些特定类型的用户。

AttributeEntity{
int id
String name;
String code;
@OneToMany
List<ApplicationVersionEntity> applicationVersionEntites
}
ApplicationEntity {
int id
String name;
String code;
boolean isActive;
}
ApplicationVersionEntity {
int id
int major;
int minor;

@ManyToOne
ApplicationEntity applicationEntity;
@ManyToOne
AttributeEntity attributeEntity;
}
FeatureEntity {
int id

@ManyToOne 
ApplicationVersionEntity applicationVersionEntity;
@ManyToOne 
ApplicationEntity applicationEntity;
String name;
boolean toBeImplemented;
}

目前我正在通过使用多个findBy:

获取结果
// fetching
ApplicationEntity app = applicatonRepo.findByCodeAndStatus("abcd",true);
AttributeEntity attribute = attributeRepo.findByName("xyz");
ApplicationVersionEntity appVersion = appVersionRepo.findByMajorMinorApplicationEntityIdAndAttributeEntityName(major,minor,activeApplication.getId(), attibute.getName());
if (application != null && appVersion != null && attribute != null){
FeatureEntity feature = new Feature();
feature.name("avoid multiple findby");
feature.setApplicationEntity(app);
feature.setApplicationVersionEntity(appVersion);
featureRepo.save(feature);
}

有没有更好更快的方法?我发现了标准构建器,但我无法使它工作。如果Cirteria Builder是正确的选择,上面有一个获取和保存的例子将非常有帮助。

如果查询不是动态的,标准生成器不会添加太多。

你可以使用@Query运行一个自定义查询,你可以检查所有的值,如果JPA是不够的,你可以尝试使用一个本地查询,这样你就不局限于JPA语法

@Query(
value = "SELECT * FROM Users u WHERE u.status = ?1", 
nativeQuery = true)
User findUserByStatusNative(Integer status);

从这里开始,问题变成了,如何建立一个查询来检查你的3个表,你可以使用UNION或类似的东西,所以只需要这个查询。

更多信息见https://www.baeldung.com/spring-data-jpa-query

最新更新