hibernate orphanRemoval生成附加的删除语句

bnl4lu3b  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(140)

我有以下内容:

class A {

 @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "a")
    private Set<B> bs;
 
 @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
 private Set<C> cs;
}

@Entity
@Table(name = "B")
@IdClass(BKey.class)
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
class B {
    @Id
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "a_id")
    private A a;

    @Id
    private String anotherKey;
}

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
public class BKey implements Serializable {

    private A a;

    private String anotherKey;
}

@Entity
@Table(name = "C")
@IdClass(CKey.class)
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
class C {
    @Id
    @ManyToOne
    @JoinColumn(name = "a_id")
    private A a;

    @Id
    private String anotherKey;
}

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
public class CKey implements Serializable {

    private A a;

    private String anotherKey;
}

当我在做
myRepo.save(objectA);
它实际上做了我需要做的,如果有类B的新项,那么就会生成insert语句,如果有一些项被删除了,那么就会因为orphanRemoval而生成delete语句,但是由于某种原因,当类C添加了新项时,然后生成正确的insert语句,但是另外生成一个delete语句,它总是删除第一个添加的项,我完全不明白。有什么原因会导致这种情况吗?当我从B中删除orphanRemoval时,不会生成delete-statement,这是预期的行为,但正如你所看到的,B和C之间没有任何关系。

vs3odd8k

vs3odd8k1#

天啊我没想到

@ManyToOne(cascade = CascadeType.ALL)

再次保存A。删除cascade = CascadeType.ALL后,一切正常。

相关问题