简体   繁体   中英

Spring, Hibernate: “collection owner not associated with session” when trying to delete

I have this problem where trying to delete a parent object via crud repository, I'm getting this error message:

"collection owner not associated with session: ClassA.things"

This error appeared after splitting one class into three (two classes extend the main classA), but I haven't done any other changes, I haven't touched this OneToMany relationship. So right now it looks approximately like this:

Class A:

@Table
@Entity(name = "ClassA")
@Inheritance(strategy = InheritanceType.JOINED)
@Getter @Setter @NoArgsConstructor @ToString
public class ClassA {

    @Column(name = "ClassA_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToMany(mappedBy = "classA", orphanRemoval = true)
    private Collection<Thing> things;

    ...etc, other fields
}

Class B and C (both extend class A):

@Table
@Entity(name = "ClassB")
@Getter @Setter @NoArgsConstructor
public class ClassB extends ClassA {

    @Column(name = "ClassB_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    ...etc, other fields
}

@Table
@Entity(name = "ClassC")
@Getter @Setter @NoArgsConstructor
public class ClassC extends ClassA {

    @Column(name = "ClassC_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    ...etc, other fields
}

And here's the Thing class, which the ClassA has a collection of with @OneToMany relationship:

@Table
@Entity(name = "Ratings")
@Getter @Setter @NoArgsConstructor
public class Thing {

    @Column(name = "Thing_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Setter(value = AccessLevel.PRIVATE)
    private int id;

    @ManyToOne
    @JoinColumn(name = "ClassA_id")
    private ClassA classA;

    ...etc, other fields
}

Finally, here's the controller method where DELETE is being called to delete ClassB, for example:

    @Transactional
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteClassB(@PathVariable(name = "id") int id) {
        if (classBservice.delete(id)) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

try to remove the id members from ClassB and ClassC since they are inherited from ClassA.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM