Hi,

1.) You probably want to create a composite ID class.

@Entity
public class UserContact {
    @Id
    String contactPhone;
    @Id
    String contactName;

    @ManyToOne
    User user;
    . . .
}

You then need to create a composite ID class. You can do this by hand,
or have the OpenJPA Application ID tool generate one for you (I'd
prefer to use the tool). Here's how I created one.

Assuming your java code is in src/main/java/
# You will need to add OpenJPA, its dependencies and
META-INF/persistence.xml to your classpath before running the command.
$ java org.apache.openjpa.enhance.ApplicationIdTool -s Id -d
src/main/java src/test/main/package/UserContact.java

This will generate src/main/java/UserContactId.java. You can then add
@IdClass to the entity and compile, enhance, package etc. Here's where
you'd add the @IdClass :
@Entity
@IdClass(value=UserContactId.class)
public class UserContact {
. . .
}

2.) If you let OpenJPA generate the tables for you (via the
MappingTool, or openjpa.jdbc.SynchronizeMappings configuration
property) it will create the tables like this (on Derby) :

CREATE TABLE MY_USER (U_ID BIGINT NOT NULL, U_NAME VARCHAR(255),
PRIMARY KEY (U_ID))
CREATE TABLE UserContact (contactName VARCHAR(255) NOT NULL,
contactPhone VARCHAR(255) NOT NULL, user_U_ID BIGINT, PRIMARY KEY
(contactName, contactPhone))
CREATE INDEX I_SRCNTCT_USER ON UserContact (user_U_ID)

Your mileage may vary on other databases :-)

Hope this helps,
-Mike


On Oct 31, 2007 12:34 PM, Ajay Aggarwal <[EMAIL PROTECTED]> wrote:
> I have 2 simple tables, user and contacts. A user may have many
> contacts. So I use OneToMany and ManyToOne in corresponding entities:
>
> Class User {
>    @Id
>    long userId;
>    String username;
>
>    @OneToMany (mappedBy="user")
>    List <UserContact> contacts;
> }
>
> Class UserContact {
>    String contactPhone;
>    String contactName;
>
>   @ManyToOne
>   User user;
> }
>
> Now I am struggling with the UserContact entity:
> Q1. How do I specify that it's PRIMARY KEY=user+contactPhone?
> Q2. How do I specify a UNIQUE constraint on a combination of
> user+contactName?
>
> Thanks.
>

Reply via email to