此代码失败
我在数据库中有一个现存的版本化值,该值是我使用entity manager.find
获取的,并在实体上进行了设置。
VersionEntity version = entityManager.find(VersionEntity.class, 1);
entities.forEach(__ -> __.setVersion(version));
entities.forEach(entityManager::persist);
entityManager.flush();
我正在专门查找并分配版本1,所以为什么它甚至尝试使用版本2。我什至尝试了merge
,但没有用。
我的属性显然是错误的/不正确的。
刷新失败
ocal异常堆栈: 异常[EclipseLink-4002](Eclipse Persistence Services-2.7.1.qualifier):org.eclipse.persistence.exceptions.DatabaseException 内部异常:org.postgresql.util.PSQLException:错误:在表“ t_quality_measurement”上插入或更新违反了外键约束“ fk_t_quality_measurement_version” 详细信息:表(t_version)中不存在键(版本)=(2)。 错误代码:0 呼叫:插入T_QUALITY_MEASUREMENT(品牌,日期,KPICODE,KPICOMPAREVW,KPICOMPAREWT,KPIVALUE,组织单位,相位,工厂,系列,信号颜色,技术,温度,视图,视图)值(?,?,?,?,?,?,?,? ?,?,?,?,?,?,?) 绑定=> [绑定14个参数] 查询:
我不确定为什么我特意查找1时为什么要使用2。
@Entity
@Table(name = "T_QUALITY_MEASUREMENT")
public class QualityMeasurementEntity extends Versioned implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
private Integer id;
@Column(length = 100)
private String series;
版本看起来像这样
@MappedSuperclass
public abstract class Versioned {
@ManyToOne
@JoinColumn(name = "version", insertable = false, updatable = false)
protected VersionEntity version = null;
public VersionEntity getVersion() { return version; }
public void setVersion(VersionEntity version) { this.version = version; }
}
和版本实体。
@Entity
@Table(name = "T_VERSION", indexes = {
@Index(name = "pk_version", columnList = "id", unique = true)
})
@NamedQuery(name = "Version.findById", query = "SELECT v FROM VersionEntity v WHERE v.id = :id")
public class VersionEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
private Integer id;
@Column(name = "CREATED")
private LocalDateTime created;
@Column
private Boolean active = false;
@PrePersist
protected void onCreate() {
created = LocalDateTime.now();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LocalDateTime getCreated() { return created; }
public void setCreated(LocalDateTime created) { this.created = created; }
public Boolean getActive() { return active; }
public void setActive(Boolean active) { this.active = active; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VersionEntity version = (VersionEntity) o;
return id.equals(version.id);
}
@Override public int hashCode() { return id.hashCode(); }
}
答案 0 :(得分:0)
There is no need to prevent the insert.
Change @JoinColumn
@JoinColumn(name = "version")