Search code examples
gwtjpaeclipselinkrequestfactory

GWT/RequestFactory/JPA foreign key not merged automatically


I have the 2 following entities:

@Entity
@Table(name = "brand")
public class Brand {

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;
}

and

@Entity
@Table(name = "car")
public class Car {

    @Id
    @Column(name = "id")
    private Integer id;

    @Version
    @Column(name = "version")
    private Integer version;

    @ManyToOne(optional=false)
    @JoinColumn(name = "brand_id", referencedColumnName = "id")
    private Brand brand;

    @Column(name = "otherproperty")
    private String otherProperty;
}

Basically the brand will be a predefined list that should never change, chosen in the GUI from a drop-down list. However, I'd like to be able to change the brand of my car as any other property.

Here is the method in my DAO:

public void updateCar(Car update) throws Exception {

    EntityManager em = entityManager();
    try {
        em.getTransaction().begin();
        em.merge(update);
        em.getTransaction().commit();

    } finally {
        em.close();
    }
}

The DAO works fine to update otherProperty, but if I provide another brand as child of the Car update parameter, it won't update the foreign key to the new brand.

I've tried using the CascadeType properties, but it wants to update the brand table, which I don't want.

Any help would be appreciated. Thanks!


EDIT: OK I've found a solution, but it looks over complicated to me.

If I add 2 lines in the DAO code in order to explicitly look for the brand to update, it works:

public void updateCar(Car update) throws Exception {

    EntityManager em = entityManager();
    try {
        em.getTransaction().begin();

        Brand lookedUp = findBrandById(update.getBrand().getId());
        update.setBrand(lookedUp);

        em.merge(update);
        em.getTransaction().commit();

    } finally {
        em.close();
    }
}

However I'm working with GWT/RequestFactory, and have implemented a Locator for my Brand and one for my Car, so I would assume the Locator would take care of that business for me.

Am I missing something?


Solution

  • How did you find the new brand entity in order to associate it to your car? Make sure that you have looked it up and changed the reference and not just modified the old brand object's id and name.