Pregunta

I have an entity A which has a one-to-one mapping to another entity B and hibernate is lazy-loading. I want to have it so it is possible to retrieve entity B directly or just entity B's foreign key right from entity A.

public class A{
    private long bfk;
    private B b;
    //setters/getters...
}

The behavior I'm looking for is when I retrieve entity A that bfk would be populated with the correct foreign key value (but b would still not be set). And when I getB() that the proper entity would be retrieved by hibernate. Also from the setting side: when I setB() hibernate would correctly populate idOfB with the foreign key. And when I setBfk() that hibernate would return the correct entity if I then retrieve getB(). Is this possible, preferably with annotations?

Just wanted to add that I think this might be somewhat similar to this question but I want to also have the entity, not just the fk.

Thank you very much in advance.

¿Fue útil?

Solución

I found that this is actually not possible in as much as being able to update via either the fk or the entity. Hibernate doesn't let you which makes complete sense. However you can populate both, you just have to pick which one will be the one that's updatable/insertable. You make both properties point to the same fk column and you're golden. So this question becomes a lot more similar once you know that so it gets an upvote. Either way here's the annotated version of how it's possible:

public class A{
    @Column(name="b_id")
    private long bfk;
    @OneToOne
    @JoinColumn(name="b_id", insertable=false, updatable=false)
    private B b;
    //other stuff...id, setters/getters etc.
}

At least in my case I think it's a lot better to have the fk as the insertable/updatable property.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top