users@glassfish.java.net

Re: One to many, qualified by type?

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

<p>Let me see if I can clarify a bit.</p>

<p>I need two things to happen at the same time, and I'm not sure how to accomplish it.</p>

<p><b>Thing one:</b> I need there to be many <tt>PersonNameEntity</tt> instances for each <tt>Person</tt> instance. To accomplish this in a vacuum, I clearly do something like this in <tt>PersonNameEntity</tt>:
<blockquote>
[code]@ManyToOne
public PersonEntity getPersonEntity() {
  return this.personEntity;
}[/code]
</blockquote></p>

<p><b>Thing two:</b> I need the database identity of a <tt>PersonNameEntity</tt> record to be determined by (a) the <tt>long</tt> primary key of the <tt>Person</tt> that it attaches to and (b) the <tt>String</tt> type of the name in question. So I need a composite primary key here, which I could conceivably do like this (in <tt>PersonNameEntity</tt>):
<blockquote>
[code]@EmbeddedId
public PersonNameEntityPK getPrimaryKey() {
  return this.primaryKey;
}[/code]
</blockquote>
...assuming, of course, the existence of a pseudocode class like this:
<blockquote>
[code]@Embeddable
public class PersonNameEntityPK implements Serializable {
  private long personEntitySerialKey;
  private String type;
}[/code]
</blockquote></p>

<p>I'm not sure how to make these two things happen at the same time! That is, if I go with the general solution for <b>thing one</b>, then OK, I have a many-to-one relationship between name and person. But I don't really have any way, now, I don't think, to say that this relationship--this many-to-one relationship whose target is a <tt>PersonEntity</tt>--is also part of what needs to be my primary key here. Conversely, if I go with the general solution for <b>thing two</b>, then OK, I have a composite primary key that should work for correctly assigning database identity, but I don't see an obvious way to force a join from "half" of that primary key--the <tt>long</tt> denoting the <tt>PersonEntity</tt> in question--to the <tt>PersonEntity</tt> table.</p>

<p>The only thing I can think of is to put both approaches in play, and annotate them appropriately with <tt>@JoinColumn</tt> annotations so that It Just So Happens That the database column that Toplink will use to implement the many-to-one relationship will be named the same thing as the column that forms half of the primary key in my <tt>@Embeddable</tt> class. And this seems like a giant hack to a really, really, really common modeling pattern.</p>

<p>I hope that clears things up and doesn't muddy the waters further. Thanks for reading.</p>

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

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