mappedBy problem

#1

If I put the mappedBy element to the @OneToMany, the owned side (the many side) will never persist !

for example

@Entity
public class Employee {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long id;
    public String name;
    @OneToMany(targetEntity=Address.class,mappedBy="employee")
    public List<Address> addresses;
}

@Entity
public class Address {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long id;
    public String line;
    @ManyToOne
    public Employee employee;
}

The address class will never persist !!

 

#2

There was a bug in cascading operations through inverse (mapped by) fields - thank you for your report.

Build 07 should fix this problem. Please try it.

You will have to add cascade=CascadeType.PERSIST to the mapped by field, unless you have global persist cascade enabled.

ObjectDB Support
#3

Using Build 07, I persist Employee  and the Address can be persisted. But there is no relationship established between the two entities! Using the explorer I see the employee field in the Address is null and there is no link to Address from Employee!

 

#4

To establish the link, you must set the owner side, e.g.

  em.getTransaction().begin();

  Employee employee = new Employee();
  employee.name = "Employee1";
  employee.addresses = new ArrayList<Address>();

  Address address1 = new Address();
  address1.line = "address1";
  address1.employee = employee;
  employee.addresses.add(address1);

  Address address2 = new Address();
  address2.line = "address2";
  address2.employee = employee;
  employee.addresses.add(address2);

  em.persist(employee);
  em.getTransaction().commit();

Actually, even if you do not set the mapped by side, it will automatically set when the object (Employee) is retrieved or refreshed from the database - as long as the owner side is set (because the mapped by side is merely a request to execute a query).

You are right about the Explorer. Currently inverse (mapped by) fields are not shown. Support of bidirectional links is a new ObjectDB 2 feature and the Explorer has not been adjusted yet.

ObjectDB Support
#5

I followed your post and I got the correct result. But the standard JPA should establish the link automatically! Is the objectdb deviated from the standard ?

#6

Not exactly - According to the JPA specification, "The owning side of a relationship DETERMINES the updates to the relationship in the database".

Therefore, if the owning side (Address) has a null - storing a relationship based on the inverse side (Employee) is against the standard.

ObjectDB Support
#7

Support of inverse (mapped by) fields is now supported by the Explorer (since version 2.0 RC1 build 08).

ObjectDB Support

Reply