Pregunta

I have one table named PLACES with one composite primary key (parent_id, version_id). It is a tree of objects, which are linked through the keys. One child has just one parent, and one parent may have many children.

How can I describe it with JPA entity?

¿Fue útil?

Solución

Use a ManyToOne relation from the child to the parent.

This is for OpenJpa. Might even work.

public class Place{

    @EmbeddedId
    PlaceId id;


    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name="PARENT_ID" referencedColumnName="ID"), // ID = matching primary key
        @JoinColumn(name="PARENT_VER" referencedColumnName="VER") //etc
    })
    public Place parent;


    @OneToMany(fetch=FetchType.LAZY, mappedBy="parent")
    public List<Place> childPlaces;


}

The OneToMany relation might be omitted if it's not needed. If I remember correctly, it needs to be managed, ie childs need to be inserted there too when creating child-places, by you, using java.


Btw.

I would advise against using a version column in a composite key in order to manually keep old versions of your data (for auditing or similar purposes) as that slows down and complicates all joins, and generally will make you miserable at some point in your life - As opposed to using a version column that is not part of a composite key, used for optimistic locking.

You might want to look into some kind of build in support for auditing/logging. OpenJpa has auditing support (OpenJPA Audit) and most database provide some support, either out-of-the-box or by using triggers. All alternatives are faster and better than using composite keys.

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