users@glassfish.java.net

One to many, qualified by type?

From: <glassfish_at_javadesktop.org>
Date: Mon, 20 Aug 2007 08:20:05 PDT

<p>I am looking for the community's recommendation on a JPA best practice.</p>

<p>I have a <tt>PersonEntity</tt> <tt>@Entity</tt>. I'm looking to implement a method like this:

<blockquote>[code]public String getName(final String type);[/code]</blockquote>

Real simple stuff.</p>

<p>Now obviously the implementation of this (<tt>@Transient</tt>) method will delegate to a JPA-friendly <tt>@OneToMany</tt>-type implementation uner the covers, and it's that that I have questions about.</p>

<p>In the database, I want there to be a <tt>Person</tt> table and a <tt>PersonName</tt> table.</p>

<p>My <tt>Person</tt> table will have a surrogate key. My <tt>PersonName</tt> table will have a composite primary key made up of the ID of the person to whom the <tt>PersonName</tt> record pertains, and the (non-<tt>null</tt>) type. The combination of <tt>personID</tt> and <tt>type</tt> must be unique.</p>

<p>I've done a ton of Googling over the last two days to see what the recommendations are for accomplishing this most common of cases. The consensus, if there can be said to be one, is something like this:
<ul>
<li><tt>PersonNameEntity</tt> should have a composite primary key implemented by way of <tt>@EmbeddedId</tt> (perhaps the class name is <tt>PersonNameEntityPK</tt>). It could use <tt>@IdClass</tt> instead; people seem to just "feel" that <tt>@EmbeddedId</tt> is somehow "better".</li>
<li>The primary key class (<tt>PersonNameEntityPK</tt>) should have two fields: <tt>long personID</tt> and <tt>String type</tt>. I guess? that <tt>personID</tt> should be annotated to be a <tt>@ManyToOne</tt>? back to the governing <tt>PersonEntity</tt>'s primary key? I'm a little foggy on how to accomplish this.</li>
<li><tt>PersonEntity</tt> should have a <tt>@OneToMany</tt> relationship with <tt>PersonNameEntity</tt>.</li>
</ul></p>

<p>This seems like a really novice question, and for that I'm sorry, but it also seems like it's not really answered well in any tutorial I can find.</p>

<p>Best,<br/>
Laird</p>
[Message sent by forum member 'ljnelson' (ljnelson)]

http://forums.java.net/jive/thread.jspa?messageID=231634