主键冲突java spring boot sql server

f4t66c6m  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(391)

在我的项目中,我有events实体和mylocation实体。
mylocation id是event.eventstarttime(isostring)+event.eventname,当我尝试更新事件名称(不再与mylocation字符串名称相关)时遇到问题,错误如下:

Violation of PRIMARY KEY constraint 'PK__my_locat__72E12F1A88A314B4'. Cannot insert duplicate key in object 'dbo.my_location'. The duplicate key value is (2020-06-25T14:00:01.235ZWeddingT&Z).

代码如下:

@Entity
@Table(name = "Events")
public class Event {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long eventID;
    @Column(nullable = false)
    private String eventName;
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private MyLocation eventLocation;
    @column
    private TimeStamp eventStartTime;
    ....
@Entity
public class MyLocation {
    @Id
    private String name;
    @Column
    private double longitude;
    @Column
    private double latitude;
    .....

问题是否与mylocation中的@id有关?或者其他解决方案?

rkkpypqq

rkkpypqq1#

好像你想复制我的位置。您是如何生成位置名的,还是对唯一的位置名有足够的检查逻辑?
您还可以使用其他类型作为事件表的主键。就像uuid。

@Id
@GeneratedValue(generator = “UUID”)
    @GenericGenerator(
        name = “UUID”,
        strategy = “org.hibernate.id.UUIDGenerator”,
    )
@Column(name = “id”, updatable = false, nullable = false)
private UUID id;

或者您可以有一个自动递增id:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

相关问题