Hibernate自连接异常:不存在具有给定标识符的行

时间:2018-05-27 20:11:45

标签: java hibernate hibernate-mapping self-join hibernate-annotations

我有一张表格如下

CREATE TABLE labour_no_pk ( id bigint(20) NOT NULL AUTO_INCREMENT, name varchar(255) DEFAULT NULL, labour_id bigint(20) NOT NULL, contractor_id bigint(20) DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY labour_id_UNIQUE (labour_id), KEY FK_SELF_idx (contractor_id), CONSTRAINT FK_SELF FOREIGN KEY (contractor_id) REFERENCES labour_no_pk (labour_id) ON DELETE CASCADE ON UPDATE CASCADE );

分组为

@Entity
@Table(name = "LABOUR_NO_PK")
public class LabourNoPK {
    @Id
    @Column(name = "id")
    @GeneratedValue
    private Long id;

    @Column(name = "firstname")
    private String firstName;

    @ManyToOne(cascade = { CascadeType.ALL })
    @JoinColumn(name = "labour_id")
    private LabourNoPK contractor;

    @OneToMany(mappedBy = "contractor")
    private Set<LabourNoPK> subordinates = new HashSet<LabourNoPK>();
}

DAO as

public static List<LabourNoPK> getLabours(Session session) {
        List<LabourNoPK> labours = null;
        try {
            Query query = session.createQuery("FROM LabourNoPK where contractor_id is null");
            labours = query.list();
            for (LabourNoPK labour : labours) {
                System.out.println("parent=" + labour.toString());
                if (null != labour.getSubordinates() && !labour.getSubordinates().isEmpty()) {
                    for (LabourNoPK subordinate : labour.getSubordinates()) {
                        System.out.println("Sub=" + subordinate.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return labours;
    }

我有数据

enter image description here

当我运行程序时,我得到org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [LabourNoPK#100]但是在DB中有可用的记录。 我理解(从异常消息中)我的模型类指向id而不是contractor_id。我应该如何映射以获得所有有孩子的父母的结果?

我到底错过了什么? 提前谢谢

1 个答案:

答案 0 :(得分:0)

经过大量阅读和试验,我能够实现我想要的。所以,如果有人需要相同的方式发布。

@Entity
@Table(name = "LABOUR_NO_PK")
public class LabourNoPK implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue
    private Long id;

    @Column(name = "labour_id")
    @NaturalId
    private Long labourId;

    @Column(name = "firstname")
    private String firstName;

    @OneToMany(mappedBy="labour")
    private Set<LabourNoPK> subordinates = new HashSet<>();

    @ManyToOne
    @JoinColumn(name = "contractor_id", referencedColumnName = "labour_id")
    /* child (subordinate) contractor_id will be matched with parent (labour) labour_id*/
    private LabourNoPK labour;

}

enter image description here