0

Let's say I have this two classes:

@Entity
public class A {
    @GeneratedValue @Id
    Integer aNum;
    ArrayList<B> bS;

    public A(){
        bS = new ArrayList<B>();
    }

    public void addB(B b){
        bS.add(b);
    }
}

and

@Entity
public class B {
    @GeneratedValue @Id
    Integer bNum;
    String text;

    public B(String t){
        this.text = t;
    }

    public String getText(){
        return this.text;
    }
}

Basically A class has an arraylist with objects from B class and I want to insert these to objectdb database:

    A a = new A();
    B b1 = new B("text1");
    B b2 = new B("text2");
    a.addB(b1);
    a.addB(b2);

    db.getTransaction().begin();
    db.persist(a);
    db.persist(b1);
    db.persist(b2);
    db.getTransaction().commit();

The problem comes when I try to remove b1 from the database. It gets removed from it's class but if I check A's arraylist it still remains there with null values. What should I do if I want it to get removed without doing it manually? I could do it manually removing b1 from the arraylist and after that removing b1 but I wonder if there is another way of removing it without the need of having to remove it manually from the arraylist.

This is what I get:

null values image

Thanks.

edit: this is how I remove

db.getTransaction().begin();
B b = db.find(B.class, 2);
System.out.println(b.getText());
db.remove(b);
db.getTransaction().commit();
ObjectDB
  • 1,312
  • 8
  • 9
AwesomeGuy
  • 537
  • 1
  • 6
  • 17

1 Answers1

0

What should I do if I want it to get removed without doing it manually?

You need to maintain @OneToMany relationship for your Entity classes A and B as shown below:

@Entity
public class A {
    @GeneratedValue 
    @Id
    Integer aNum;

    @OneToMany(mappedBy="department", cascade={CascadeType.ALL})
    List<B> bS;

    //getters and setters
}


@Entity
public class B {
    @GeneratedValue 
    @Id
    Integer bNum;

    String text;

    @ManyToOne
    @JoinColumn(name = "aNum")
    private A a;

    //getters and setters
}

You can refer here for understanding the API and look here for very simple example on the same concept.

Vasu
  • 21,832
  • 11
  • 51
  • 67