如何检查 class 实例是否存在

how to check existence of a class instance

我想检查我的 Woman class 中是否存在一个字段。该字段是它自己的 (Husband) class,Woman 和 Husband 都是存储在数据库中的实体。 Husband class 未在 Woman class 的构造函数中初始化。稍后在程序中,在我操作了 Woman class 的一些实例之后,我想检查 Woman class 的哪些条目仍然没有 Husband class 实例(以防万一初始化它们)。我需要用 JpaQueries API 来做到这一点。基本上我想编写规范 "WithNoHusband" 来查看我的数据库。

到目前为止,我已经尝试过

(root,query,cb) -> { 
    Join<Woman, Husband> husbandJoin = root.join(husband); 
    return cb.equal(husbandJoin.isNull(), true); 
};

在我的 JpaWomanSpecificationAdapter class 和

@Value
class WithNoHusband implements WomanSpecification {

@Override
public boolean isSatisfiedBy(Woman object) {
        return object.getHusband() == null;
}

}

在我的 WomanSpecification class 中运气不佳。

当我想查看女人是否有车时,我需要做的就是

private org.springframework.data.jpa.domain.Specification<Woman> toJpaSpecification(WithNoCar specification) {
    (root,query,cb) -> cb.isEmpty(root.get(car)); 
}

@Value
class WithNoCar implements WomanSpecification {

@Override
public boolean isSatisfiedBy(Woman object) {
        return object.getCar().isEmpty();
    }
}

在相应的 classes.

这是三个classes的基本结构

 public class Woman{ 

    @Id
    Integer id;
    @Column
    String name;
    @OneToOne(mappedBy = "maintenanceImplementation", cascade = ALL, orphanRemoval = true)
    @Getter
    Husband husband;
    @oneToMany(mappedBy = "maintenanceImplementation", cascade = ALL, orphanRemoval = true)
    @Getter
    List<Car> car;
    @Column
    @Enumerated(STRING)
    @Getter
    Type typeOfWoman;

    public Woman(Integer id, String name){
        this.is=id;
        this.name=name;
        this.car = new ArrayList<>();
    }
}

public class Husband {

    @Id
    Integer Id;
    @OneToOne
    @JoinColumn(name = "WomanId", nullable = false)
    @Getter
    @Setter(PACKAGE)
    private Woman Woman;
    @Column
    String name;
}

public class Car {
    @Id
    Integer Id;
    @ManyToOne
    @JoinColumn(name = "WomanId", nullable = false)
    @Getter
    @Setter(PACKAGE)
    private Woman Woman;
    @Column
    String brand;
}

我期望的是,对于 Husband,规范 withNoHusband 将 return 符合 isNull 条件。

当然,Car 在 Woman 的构造函数中被初始化为空列表,因此可以简单地查询该列表是否为空(无需拼写 join 子句 ) 但是在 husband 的 join 子句到位之后,查询结果 select all women without cars and without husband 仍然是

unexpected AST node: is near line 1, column 485 [select generatedAlias0 
from Woman as generatedAlias0, Woman as generatedAlias1 inner join
generatedAlias1.husband as generatedAlias2 where ( ( 
generatedAlias0.status=:param0 ) and ( generatedAlias0.cars is empty ) ) and 
( generatedAlias2 is null=:param1 )]

?

PS:我不需要在 WOMAN 的构造函数中初始化丈夫,因为(到目前为止)丈夫的存在是基于 typeOfWoman,所以如果 typeOfWoman 是 "widow",丈夫不需要初始化。

FEI,我犯的错误是创建了一个 INNER JOIN 子句(在标准 API 中默认)(root,query,cb) -> { Join husbandJoin = root.join(husband , 剩下); return cb.equal(husbandJoin.isNull(), 真); };成功了...