Hibernate Persistencebag remove element from list

I have two entities:

the first one:

    @Entity
    public class A{

    @OneToMany(mappedBy = "a", targetEntity = B.class, ...)
        @LazyCollection(LazyCollectionOption.FALSE)
        private List<B> b;

getter and setter

    }

and the second one:

@Entity
public class B{

@ManyToOne(targetEntity = A.class, ...)
    @JoinColumn(name = "aId",...)
    private A a;

now i read the data from the database and i want to remove some elements:

List<B> bList = a.getB();
for(B b: bList)
    if(some condiction)
      bList.remove(b)

why i can't? why is bList a persistanceBag and not an ArrayList? How can remove items from bList? why can i see only one item in the debug modus?

Thanks Chees

Answers


Hibernate uses a proxy list to implement LAZY initialization and intercept any changes happening on the list, that's why it replaces the ArrayList with its own PersistenceBag implementation.

Simply add orphan-removal to your one-to-many association:

@OneToMany(mappedBy = "a", targetEntity = B.class, orphanRemoval = true)
private List<B> b = new ArrayList<>();

and then remove the element from the list:

B toBeRemoved = ...;
a.b.remove(toBeRemoved);
toBeRemoved.a = null;

Need Your Help

Response.Flush() only works with Firefox

asp.net internet-explorer-8 google-chrome

I am trying to send some content to the client before doing some lengthy work: