我正在尝试进行双向一对一关系,当在第一次保存时更新AccountExtrasModel时,它可以正常工作,但在更新时,我会收到一个错误,或者sql语句会添加一个insert,然后添加一个delete,而不是更新。
import lombok.*;
import javax.persistence.*;
@ToString
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "Account")
public class AccountModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Account_ID;
@Column(nullable = false, updatable = false)
private String name;
@Column(nullable = false, unique = true, updatable = false)
private String email;
@Column(nullable = false, updatable = false)
private String password;
@OneToOne(mappedBy = "accountModel", cascade = CascadeType.ALL, orphanRemoval = true)
private AccountExtrasModel accountExtras;
public AccountModel addExtras(AccountExtrasModel accountExtrasModel) {
accountExtrasModel.setAccountModel(this);
this.setAccountExtras(accountExtrasModel);
return this;
}
}
import lombok.*;
import javax.persistence.*;
@Setter
@Getter
@NoArgsConstructor
@ToString
@Entity
@Table(name = "AccountExtras")
public class AccountExtrasModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long ID;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private AccountModel accountModel;
@Lob
private String description;
private String[] myVideos;
private String[] likedVideos;
private String imageReference;
}
如果在AccountExtrasModel中将@MapsId更改为@JoinColumn,则会得到所需的结果,但它所做的是插入新行并将其链接到Account,然后删除旧行,而不是执行更新。
这是我得到的错误:
{
"timestamp": "2018-04-26T18:19:01.657+0000",
"status": 500,
"error": "Internal Server Error",
"message": "A different object with the same identifier value was already associated with the session : [com.alttube.account.models.AccountExtrasModel#1]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.alttube.account.models.AccountExtrasModel#1]",
"path": "/update_account"
}
要获得所需的结果,只需在accountExtrasModel上对其所属的相应帐户执行更新,我可以做些什么?