Rasmus Franke
Rasmus Franke

Reputation: 4524

JPA, Combine @JoinColumn and @Column

Is it possible to use both @JoinColumn and @Column for the same field in JPA, enabling updates from both?

Lets say I have an entity like this:

@Entity
public class Person{
    @JoinColumn(name = "address_id", referencedColumnName = "id")
    @ManyToOne
    private Address address;

    // getters and setters
}

Assuming the Address object already exists - when creating this object, I need to fetch the address from the database before persisting a Person. This is my current design throughout my application, but it can cause performance issues. Is it possible to add the possibility to persist by use of ID only, while keeping possibility to persist with the real object (for not having to change huge amounts of code elsewhere)? Something like this

@Entity
public class Person{
    @JoinColumn(name = "address_id", referencedColumnName = "id")
    @ManyToOne
    private Address address;

    @Column(name="address_id")
    private Integer addressId;

    // getters and setters
}

em.persist(new Person(1));
em.persist(new Person(getAddress(1)));

Is it possible to annotate to allow for both these persist lines? MY current belief is that one of the fields need to have insertable = false

Upvotes: 6

Views: 5930

Answers (1)

Adam Dyga
Adam Dyga

Reputation: 8896

Such duplicate mapping is not possible, because it could lead to conflicts. What if you set the address field to an Address with ID = X, and then addressId to another ID = Y? Which one should JPA take into account on save? That's why you have to specify it and make one of those fields insertable=false, updatable=false.

A solution to your problem is EntityManager.getReference() method. It returns a "proxy" object for given class and ID without actually loading it from DB. This way you can set the address reference in Person object and persist it:

em.persist(new Person(em.getReference(Address.class, 1)));

Thanks to this solution you don't need the addressId field at all.

Upvotes: 3

Related Questions