代码之家  ›  专栏  ›  技术社区  ›  Extreme

休眠自联接异常:不存在具有给定标识符的行

  •  0
  • Extreme  · 技术社区  · 6 年前

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

    道作

    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] 但数据库中有可用的记录。 我理解(从异常消息)我的模型类指向 id 而不是 contractor_id . 我应该如何映射以获得所有有孩子的父母的结果?

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

    1 回复  |  直到 6 年前
        1
  •  0
  •   Extreme    6 年前

    经过大量的阅读和试验,我能够达到我想要的。所以,如果有人需要同样的方式,就张贴。

    @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