persistence@glassfish.java.net

Re: Simple foreign keys

From: Gordon Yorke <gordon.yorke_at_oracle.com>
Date: Mon, 07 Dec 2009 09:07:08 -0400

The easiest mechanism is to map this field as a @Basic but ensure you
also use @Column and set 'updatable=false, insertable=false'.
Alternatively you can create a JPQL query that returns the ID directly.
--Gordon

bht_at_actrix.gen.nz wrote:
> Hi,
>
> Is there support for reading the simple foreign key field value of a
> @ManyToOne related entity as it is stored in the database, without
> forcing EntityManager to fetch the related entity?
>
> I need this when I process an ordered result list in groups of the
> related parent entity. Unfortunately, caching does not work in this
> case, and EntityManager re-fetches the parent entity on every call
> child.getParent().getId(). I only need the ID to detect change of
> group.
>
> I know I can completely remove the relationship and work exclusively
> with an ID field. But then I lose all foreign key constraints
> generated by TopLink DDL.
>
> Before I take this option I would like to know whether there is any
> other best practice for this type of scenario.
>
> I have tried to use BOTH
>
> @Column(name="parent_id")
> private Integer parentId;
>
> AND
>
> @ManyToOne
> @JoinColumn(name="parent_id", nullable = true, insertable=false,
> updatable=false)
> private Category parent;
>
> with the same coumn name, but then I get exceptions, one of them
> unexplainable (cannot find parent that was inserted before), so I am
> not sure whether I am dealing with a TopLink bug.
>
> Many thanks
>
> Bernard
>
>