Hibernate Criteria Return parent record that have one-to-one child record not null?

心已入冬 提交于 2019-12-20 06:39:51

问题


I have a one-to-one relation like this

The Parent

@JsonAutoDetect
@Entity
@Table(name = "Parent")
public class Parent{

    private Integer id;
    private Child child;

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column (name="idparent")
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
    @JoinColumn(name="idchild", nullable=true)
    public Child getChild() {
        return child;
    }
    public void setChild(Child child) {
        child.setParent(this);
        this.child = child;
    }
}

and the child

@JsonAutoDetect
@Entity
@Table(name="Child")
public class Child{

    private Integer id;
    private Parent parent;

    @Id
    @GeneratedValue(generator = "foreign")
    @GenericGenerator(name = "foreign", strategy = "foreign", parameters = { @Parameter(name = "property", value = "parent") })
    @Column (name = "idchild")
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    @OneToOne(fetch = FetchType.LAZY, optional = true)
    @Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
    @PrimaryKeyJoinColumn
    @JsonIgnore
    public Parent getParent() {
        return parent;
    }
    public void setParent(Parent parent) {
        this.parent= parent;
    }

}

I want to create criteria that return the parent that have child isNotNull, i tryed somme think like

Criteria criteria = session.createCriteria(Parent.class);
criteria.add(Restrictions.isNotNull("child"));

But not work, can you help me by giving somme example please ? Thanks


回答1:


First of all, the mapping is wrong. In the parent class, you're saying that the association is mapped by child.parent, and immediately after you're saying that it's mapped using a join column named id_child. Make up your mind. Either it's mapped by the child.parent property, and you should remove the @JoinColumn. Or it's mapped by the JoinColumn and you should remove the @PrimaryKeyJoinColumn in the child, and use mappedBy="child" in the Child entity.

Now, to make your query work, whatever the mapping is, you should simply make an inner join:

Criteria criteria = session.createCriteria(Parent.class);
criteria.createAlias("child"); // inner join

Since the join is an inner join, it will only select parents that have a non-null child.



来源:https://stackoverflow.com/questions/12776847/hibernate-criteria-return-parent-record-that-have-one-to-one-child-record-not-nu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!