我想测试所有 Hibernate 关联注释(@ManyToOne、@OneToMany、@OneToOne、@ManyToMany)都在使用fetch = FetchType.LAZY
. 这是有效的:
private static final Set<Class<? extends Annotation>> associations =
Set.of(ManyToOne.class, OneToMany.class, OneToOne.class, ManyToMany.class);
@ArchTest
public static final ArchRule allEntityRelationsShouldBeLazy = fields().that()
.areDeclaredInClassesThat().areAnnotatedWith(Entity.class)
.and()
.areAnnotatedWith(ManyToOne.class)
.or().areAnnotatedWith(OneToMany.class)
.or().areAnnotatedWith(OneToOne.class)
.or().areAnnotatedWith(ManyToMany.class)
// what I'd like: .areAnnotatedWith(Any.of(associations))
.should()
.notBeAnnotatedWith(new DescribedPredicate<>("FetchType.EAGER or undefined FetchType") {
@Override
public boolean apply(JavaAnnotation<?> input) {
JavaClass rawType = input.getRawType();
if (!rawType.isEquivalentTo(OneToOne.class)
// what I'd like: if (!Any.of(associations).apply(input)) {
&& !rawType.isEquivalentTo(OneToMany.class)
&& !rawType.isEquivalentTo(ManyToOne.class)
&& !rawType.isEquivalentTo(ManyToMany.class)) {
// Filter again, because a field can contain multiple annotations.
return false;
}
return input.get("fetch")
.transform(JavaEnumConstant.class::cast)
.transform(fetchType -> !FetchType.LAZY.name().equals(fetchType.name()))
.or(true);
}
});
我必须过滤两次,因为一个字段可以有几个注释,如下所示:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "otherEntity", referencedColumnName = "id")
private OtherEntity otherEntity;
我不喜欢的是我必须写两次注释(ManyToOne…)。为什么 ArchUnit 中没有“anyOf”谓词?或者有没有其他方法可以避免重复它们?