JPA:在一个表中的主键列和另一个表中的非主列之间创建约束?

时间:2013-12-18 19:06:59

标签: jpa

我正在使用JPA并尝试弄清楚如何在一个表中的主键列和另一个表中的非主键列之间创建唯一约束。我有两张桌子:

Customer (
    id character varying(32) NOT NULL,
    customer_name character varying(50)
)

Account (
    id character varying(32) NOT NULL,
    account_name character varying(50)
)

客户和帐户之间存在单向,一对多的关系,其约束条件是Account.account_name对于每个客户是唯一的。代码如下:

@Entity
public class Customer {
    @Id
    @Column(length=32)
    private String id;

    @Column(unique=true, length=50)
    private String customer_name;

    @OneToMany
    private List<Account> accounts;
    ...
}

@Entity
public class Account {
    @Id
    @Column(length=32)
    private String id;

    @Column(length=50)
    private String account_name;
    ...
}

默认情况下会创建一个连接表:

CUSTOMER_ACCOUNTS (
    customer_id character varying(32),
    accounts_id character varying(32)
)

如何创建唯一约束以确保每个客户的Account.account_name是唯一的?

1 个答案:

答案 0 :(得分:1)

将JoinColumn注释添加到Customer类::

@Entity
public class Customer {
    @Id
    @Column(length=32)
    private String id;

    @Column(unique=true, length=50)
    private String customer_name;

    @OneToMany(mappedBy="customer")
    @JoinColumn(name="CUSTOMER_ID", referencedColumnName="ID")
    private List<Account> accounts;
    ...
}

引用的列名称指向Customer表的主键,而name指向Account表的外键字段。 您还应该向帐户实体添加CUSTOMER_ID字段和复合唯一约束:

@Entity
@Table(
    uniqueConstraints=
        @UniqueConstraint(columnNames={"CUSTOMER_ID", "ACCOUNT_NAME"})
)
public class Account {
    @Id
    @Column(length=32)
    private String id;

    @Column(length=50)
    private String account_name;

    @Column(name="CUSTOMER_ID")
    private String customer_id;
    ...
}