gpt4 book ai didi

java - JPA 集合在映射表中有不需要的唯一约束

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:11 25 4
gpt4 key购买 nike

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

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;

最佳答案

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

因为由 scanid 组成的唯一约束和 alert_id是首选,我假设 Scan 之间的关系和 Alert确实具有多对多的性质。那可以实现如下:

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

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

关于java - JPA 集合在映射表中有不需要的唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15972549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com