休眠一对一条件获取

时间:2019-12-03 07:53:57

标签: java hibernate jpa spring-data-jpa

我正在使用汽车和人表之间的休眠一对一映射。但是一个人可能有车,也可能没有车。现在,当使用休眠条件从人员表中获取记录时,我只想获取拥有汽车的人员,即人员表中仅存在对应于汽车表中条目的那些条目。如何使用休眠条件/别名来做到这一点?

下面是一段代码。请协助获取结果的标准或别名:

@Getter
@Setter
@Entity
@Table(name = "Person")
public class Person implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Person_ID")
    private Long personId;

    @OneToOne(mappedBy = "personAsset", cascade = CascadeType.ALL)
    private Car car;
}

@Getter
@Setter
@Entity
@Table(name = "Car")
public class Car implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Car_ID")
    private Long carId;

    @OneToOne
    @JoinColumn(name = "Person_ID")
    private Person personAsset;
}

2 个答案:

答案 0 :(得分:0)

您正在寻找的是orphanRemoval=true注释上的cascadeType @OneToOne

您的课程如下所示:

@Getter
@Setter
@Entity
@Table(name = "Car")
public class Car implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Car_ID")
    private Long carId;

    @OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL, orphanRemoval=true)
    @JoinColumn(name = "Person_ID")
    private Person personAsset;
}

答案 1 :(得分:0)

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> query = cb.createQuery(Person.class);
Root<Person> person = query.from(Person.class);
Predicate predicate = cb.isNotNull(person.join("car"));
predicates.add(predicate );