【问题标题】:Hibernate self join exception: No row with the given identifier exists休眠自联接异常:不存在具有给定标识符的行
【发布时间】:2018-05-27 20:11:45
【问题描述】:

我有一张如下表

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 作为

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;
    }

我有数据

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

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

【问题讨论】:

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


    【解决方案1】:

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

    @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;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 2015-06-02
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多