Mark Estrada
Mark Estrada

Reputation: 9191

Regarding relationship management in JPA2

I am getting confused about managing entities in a relationship. According to the book PRO JPA2, relationship should be manually configured and assigned at both ends of the relationship.

Now, consider this relationship.

@Entity
public class Employee {
    ..
    @ManyToOne(cascade=CascadeType.PERSIST)
    private Department department;
    ..
}
@Entity
public class Department {
    ..
    @OneToMany(mappedBy="department")
    private Set<Employee> employees = new HashSet<Employee>();

    public void addEmployee(Employee e){
        getEmployees().add(e);
        e.setDepartment(this);
    }
}

I made a simple test case that involves this line of code to verify this.

Department dept1 = new Department();
dept1.setName("MARKETING");

Employee e1 = new Employee();
e1.setName("JOHN DOE");

e1.setDepartment(dept1); //[1]
//dept1.addEmployee(e1); //[2]

Consider Line [1]:

I thought this would not properly update the Employee table with the correct department ID but I checked Derby and it is able to properly execute the update.

Consider Line [2]:

This is the proper way according to the book.

Eclipselink/Derby/JPA2

Upvotes: 0

Views: 85

Answers (1)

damian
damian

Reputation: 4044

If you do it like in line [1], the Employee 'e1' will be stored in database with the FK ok, but... If you get Department dept1 and invoke getEmployees(); Employee 'e1' will not be in this list. Even if you make a new query to get that deparment from database again; it will not have Employee 'e1' (at least not until you reploy the application). That is why you should always do it in way [2].
When I started working with JPA2 I didn't know this; and was persisting entities like in [1]. I almost went crazy trying to determine why the recently persisted entities were not read by JPA, but were actually stored in the DB.

Upvotes: 1

Related Questions