9

I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA?
I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good.

In the following snippet, I need the command and model to be unique. pk is of course the primary key.

@Entity
@Table(name = "dm_action_plan")
public class ActionPlan {
    @Id
    private int pk;
    @Column(name = "command", nullable = false)
    private String command;
    @Column(name = "model", nullable = false)
    String model;
}
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
homaxto
  • 5,428
  • 8
  • 37
  • 53

2 Answers2

19

You can use @UniqueConstraint something like this :

@Entity
@Table(name = "dm_action_plan",
       uniqueConstraints={ @UniqueConstraint(columnNames= "command","model") } )
public class ActionPlan {
    @Id
    private int pk;

    @Column(name = "command", nullable = false)
    private String command;

    @Column(name = "model", nullable = false)
    String model;
}

This will allow your JPA implementation to generate the DDL for the unique constraint.

Michel
  • 2,454
  • 3
  • 20
  • 28
  • 1
    The correct form is like this: @Table(name = "dm_action_plan") @UniqueConstraint(columnNames = {"command", "model"}) – homaxto Sep 18 '08 at 09:01
  • homaxto: According to the EJB3.0 specification, Michel gave the right form. – Nicolas Sep 18 '08 at 09:13
1

Use @GeneratedValue to indicate that the key will be generated and @UniqueConstraint to express unicity

@Entity
@Table(name = "dm_action_plan"
       uniqueConstraint = @UniqueConstraint({"command", "model"})
)
public class ActionPlan {
    @Id
    @GeneratedValue
    private int pk;
    @Column(name = "command", nullable = false)
    private String command;
    @Column(name = "model", nullable = false)
    String model;
}
Nicolas
  • 24,509
  • 5
  • 60
  • 66
  • It will not create a compound constraint. It will create two constraints, each one for each column name that you annoted in @UniqueConstraint. – mannysz Jul 29 '11 at 19:38
  • 1
    Then your JPA implementation is wrong. JPA2 specification, §11.1.49 columnNames is "An array of the column names that make up the **constraint**" (constraint, not constraints). – Nicolas Jul 30 '11 at 06:43