我有两个模型,UserModel
和RoleModel
,它们用@OneToOne
关系Map。当我更新用户详细信息时,它首先将数据插入角色表,然后将这些新角色更新为UserModel
。
用户模型.java
package com.example.demo.Model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="Users")
public class UserModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private Integer id;
@Column(name="name")
private String name;
@Column(name="address")
private String address;
@JoinColumn(name = "role", insertable=false, nullable = false, updatable = false)
@OneToOne(cascade = CascadeType.ALL)
private RoleModel roleModel;
public UserModel() {
}
public UserModel(Integer id, String name, String address,RoleModel roleModel) {
super();
this.id = id;
this.name = name;
this.address = address;
this.roleModel = roleModel;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public RoleModel getRoleModel() {
return roleModel;
}
public void setRoleModel(RoleModel roleModel) {
this.roleModel = roleModel;
}
}
角色模型.java
package com.example.demo.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="Roles")
public class RoleModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="role")
private Integer role;
@Column(name="rolename")
private String roleName;
@OneToOne(mappedBy = "roleModel")
private UserModel userModel;
public RoleModel() {
}
public RoleModel(Integer role, String roleName) {
super();
this.role = role;
this.roleName = roleName;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
我想更新UserModel
和角色,但是这里RoleModel
插入了一个新行,然后它就更新了。请帮助我解决这个问题。告诉我应该使用的确切代码,以便只更新来自UserModel
关联角色的数据。
2条答案
按热度按时间332nm8kg1#
我建议首先研究spring关系注解是如何工作的。您明确表示,当您在
UserModel
中操作RoleModel
对象时,不应插入或更新该对象,因此即使您使用所需的值修改了正确的信息,它也不会反映在DB端。因此,如果从Map中删除
insertable=false
和updatable=false
,它将工作(考虑到右列也被Map)。此外,我建议研究一些关于Spring JPA One-to-One mappings的教程。
mfpqipee2#
请将
CascadeType
更改为detach
,这是我的工作。希望它能帮助你。