JPA Collection在映射表中具有不需要的唯一约束

时间:2013-04-12 13:23:03

标签: java spring hibernate jpa

当我使用hibernate.hbm2ddl.auto=create自动生成数据库时,正在映射表中创建“不需要的”唯一约束。我正在运行postgres 9.1,create table语句变为:

CREATE TABLE schemaname.scanalerts
(
  scanid bigint NOT NULL,
  alerts_id bigint NOT NULL,
  CONSTRAINT fkd65bd7541b5b1a8e FOREIGN KEY (scanid)
      REFERENCES rfid.scan (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkd65bd754860b0886 FOREIGN KEY (alerts_id)
      REFERENCES rfid.alert (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT scanalerts_alerts_id_key UNIQUE (alerts_id ),
  CONSTRAINT scanalerts_scanid_alerts_id_key UNIQUE (scanid , alerts_id )
)

不受欢迎的约束是CONSTRAINT scanalerts_alerts_id_key UNIQUE (alerts_id ),基本上我只想要对scanid和alerts_id进行唯一约束。

我正在使用JPA注释来创建映射,这是我的代码:

@ElementCollection(targetClass = Alert.class, fetch = FetchType.EAGER)
@CollectionTable(name = "scanalerts", schema = RfidConstants.SCHEMA, 
    joinColumns = @JoinColumn(name = "scanid"), 
    uniqueConstraints = @UniqueConstraint(columnNames = { "scanid", "alerts_id" }))
private List<Alert> alerts;

有没有办法停止创建alert_id唯一约束?

由于

@JBNizet以下是警报映射注释:

@Entity
@Table(name = "alert", schema = "schemaname", 
    uniqueConstraints = @UniqueConstraint(columnNames = {"message", "alertPriority"}) )
public class Alert implements Serializable {

    @Id
    @Column(name="id")
    @SequenceGenerator(name = "alertSeq", sequenceName="ALERT_SEQ", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "alertSeq")
    private Long id;

    @Column(name="versionnum")
    @Version
    private Long version;

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

    @Column(name = "alertpriority", nullable = false)
    @Enumerated(EnumType.STRING)
    private AlertPriority alertPriority;

2 个答案:

答案 0 :(得分:9)

JavaDocs中所述,@ElementCollection用于映射基本类型或嵌入式的集合。 Alert是一个实体,因此 List<Alert>不是基本类型或嵌入式的集合。

由于首选包含scanidalert_id的唯一约束,我认为ScanAlert之间的关系确实具有多对多性质。那 可以实现如下:

@ManyToMany
@JoinTable(name = "scanalerts",  schema = RfidConstants.SCHEMA,
  joinColumns = @JoinColumn(name = "scanid"),
  inverseJoinColumns = @JoinColumn(name = "alert_id")
)
private List<Alert> alerts;

表的主键包含两列,这就是不需要使用@UniqueConstraint的原因。

答案 1 :(得分:0)

创建的约束在此处声明:

uniqueConstraints = @UniqueConstraint(columnNames = { "scanid", "alerts_id" }))

只需删除此内容并在每个属性的Alert实体内声明约束。