Spring 插入 entity/object 时如何自动插入外键 引导 JPA 到 MySQL
How to auto insert foreign key when insert entity/object by Spring Boot JPA to MySQL
我试图插入一个实体,该实体包含从 Spring 引导 JPA 到 MYSQL 的外键。但是得到错误:
java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.
我知道在不允许为空的列中插入空值是一个错误。我知道修复(请参阅下面的 myMainController)是获取对象角色(外键)设置到我的用户对象中,然后将用户对象插入数据库(数据库中的新行)(角色的必要数据已经在数据库中)。但是我想当我插入用户时,它会自动插入对象角色,因为我已经清楚地设置了realtion(更多信息请参阅我在用户实体和角色实体中的图片)。请看我的代码。
这是错误:
java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.
这是 myMainRestController
@RestController
public class MyMainController {
@Autowired
private UserRepository service;
@RequestMapping("/i")
@ResponseBody
public String Welcome() {
return "Welcome!";
}
@JsonIgnore
@RequestMapping(value = "/", //
method = RequestMethod.GET, //
produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public User initData() {
User user = new User();
user.setUserId(4);
user.setPassword("1234");
user.setFullname("Nguyễn Văn D");
user.setPhonenumber("012345678");
user.setAddress("2 đường Số 7 Bình Trị Dông");
user.setFontIdCardImg("p2fontid.jpg");
user.setBackIdCardImg("p2backid.jpg");
user.setRoleId(2);
user.setAreaId(2);
// Role role = new Role();
// role.setRoleId(user.getRoleId()); / My fix here
// user.setRole(role);
service.save(user);
return user;
}
}
这是我的用户实体:
@Entity
@Table(name="user")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="user_id", unique=true, nullable=false)
private Integer userId;
@Column(length=1000)
private String address;
@Column(name="area_id")
private Integer areaId;
@Column(name="back_id_card_img", length=200)
private String backIdCardImg;
@Column(name="font_id_card_img", length=200)
private String fontIdCardImg;
@Column(length=45)
private String fullname;
@Column(length=45)
private String password;
@Column(length=45)
private String phonenumber;
@Column(name="role_id")
private Integer roleId;
//bi-directional many-to-one association to Accident
@OneToMany(mappedBy="user")
private List<Accident> accidents;
//bi-directional many-to-one association to Area
@ManyToOne
@JoinColumn(name="area_area_id")
private Area area;
//bi-directional many-to-one association to Policeworktime
@ManyToOne
@JoinColumn(name="policeworktime_police_user_id")
private Policeworktime policeworktime;
//bi-directional many-to-one association to Role
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="role_role_id", nullable=false)
private Role role;
public User() {
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAreaId() {
return this.areaId;
}
public void setAreaId(Integer areaId) {
this.areaId = areaId;
}
public String getBackIdCardImg() {
return this.backIdCardImg;
}
public void setBackIdCardImg(String backIdCardImg) {
this.backIdCardImg = backIdCardImg;
}
public String getFontIdCardImg() {
return this.fontIdCardImg;
}
public void setFontIdCardImg(String fontIdCardImg) {
this.fontIdCardImg = fontIdCardImg;
}
public String getFullname() {
return this.fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhonenumber() {
return this.phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public List<Accident> getAccidents() {
return this.accidents;
}
public void setAccidents(List<Accident> accidents) {
this.accidents = accidents;
}
public Accident addAccident(Accident accident) {
getAccidents().add(accident);
accident.setUser(this);
return accident;
}
public Accident removeAccident(Accident accident) {
getAccidents().remove(accident);
accident.setUser(null);
return accident;
}
public Area getArea() {
return this.area;
}
public void setArea(Area area) {
this.area = area;
}
public Policeworktime getPoliceworktime() {
return this.policeworktime;
}
public void setPoliceworktime(Policeworktime policeworktime) {
this.policeworktime = policeworktime;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
}
这是我的角色实体:
@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;
@Column(name="role_name", length=45)
private String roleName;
//bi-directional many-to-one association to User
@OneToMany(mappedBy="role", cascade={CascadeType.ALL})
private List<User> users;
public Role() {
}
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public User addUser(User user) {
getUsers().add(user);
user.setRole(this);
return user;
}
public User removeUser(User user) {
getUsers().remove(user);
user.setRole(null);
return user;
}
}
您不需要创建 Colunm roleId。您只需将关系与表格放在一起。例如,在我的情况下,我有一个具有角色的 OneToMany 用户。我只在我的 MySql 数据库中建立了关系。然后,您可以创建自己的实体或随意使用 JPA 工具。用户实体有一个对象Role,Role实体有一个List。
@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;
@Column(name="role_name", length=45)
private String roleName;
//bi-directional many-to-one association to User
@OneToMany(mappedBy="role")
private List<User> users;
public Role() {
}
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public User addUser(User user) {
getUsers().add(user);
user.setRole(this);
return user;
}
public User removeUser(User user) {
getUsers().remove(user);
user.setRole(null);
return user;
}
}
@Entity
@Table(name = "user")
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
// bi-directional many-to-one association to Role
@ManyToOne
@JoinColumn(name = "role_role_id", nullable = false)
private Role role;
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
}
我试图插入一个实体,该实体包含从 Spring 引导 JPA 到 MYSQL 的外键。但是得到错误:
java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.
我知道在不允许为空的列中插入空值是一个错误。我知道修复(请参阅下面的 myMainController)是获取对象角色(外键)设置到我的用户对象中,然后将用户对象插入数据库(数据库中的新行)(角色的必要数据已经在数据库中)。但是我想当我插入用户时,它会自动插入对象角色,因为我已经清楚地设置了realtion(更多信息请参阅我在用户实体和角色实体中的图片)。请看我的代码。
这是错误:
java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.
这是 myMainRestController
@RestController
public class MyMainController {
@Autowired
private UserRepository service;
@RequestMapping("/i")
@ResponseBody
public String Welcome() {
return "Welcome!";
}
@JsonIgnore
@RequestMapping(value = "/", //
method = RequestMethod.GET, //
produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public User initData() {
User user = new User();
user.setUserId(4);
user.setPassword("1234");
user.setFullname("Nguyễn Văn D");
user.setPhonenumber("012345678");
user.setAddress("2 đường Số 7 Bình Trị Dông");
user.setFontIdCardImg("p2fontid.jpg");
user.setBackIdCardImg("p2backid.jpg");
user.setRoleId(2);
user.setAreaId(2);
// Role role = new Role();
// role.setRoleId(user.getRoleId()); / My fix here
// user.setRole(role);
service.save(user);
return user;
}
}
这是我的用户实体:
@Entity
@Table(name="user")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="user_id", unique=true, nullable=false)
private Integer userId;
@Column(length=1000)
private String address;
@Column(name="area_id")
private Integer areaId;
@Column(name="back_id_card_img", length=200)
private String backIdCardImg;
@Column(name="font_id_card_img", length=200)
private String fontIdCardImg;
@Column(length=45)
private String fullname;
@Column(length=45)
private String password;
@Column(length=45)
private String phonenumber;
@Column(name="role_id")
private Integer roleId;
//bi-directional many-to-one association to Accident
@OneToMany(mappedBy="user")
private List<Accident> accidents;
//bi-directional many-to-one association to Area
@ManyToOne
@JoinColumn(name="area_area_id")
private Area area;
//bi-directional many-to-one association to Policeworktime
@ManyToOne
@JoinColumn(name="policeworktime_police_user_id")
private Policeworktime policeworktime;
//bi-directional many-to-one association to Role
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="role_role_id", nullable=false)
private Role role;
public User() {
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAreaId() {
return this.areaId;
}
public void setAreaId(Integer areaId) {
this.areaId = areaId;
}
public String getBackIdCardImg() {
return this.backIdCardImg;
}
public void setBackIdCardImg(String backIdCardImg) {
this.backIdCardImg = backIdCardImg;
}
public String getFontIdCardImg() {
return this.fontIdCardImg;
}
public void setFontIdCardImg(String fontIdCardImg) {
this.fontIdCardImg = fontIdCardImg;
}
public String getFullname() {
return this.fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhonenumber() {
return this.phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public List<Accident> getAccidents() {
return this.accidents;
}
public void setAccidents(List<Accident> accidents) {
this.accidents = accidents;
}
public Accident addAccident(Accident accident) {
getAccidents().add(accident);
accident.setUser(this);
return accident;
}
public Accident removeAccident(Accident accident) {
getAccidents().remove(accident);
accident.setUser(null);
return accident;
}
public Area getArea() {
return this.area;
}
public void setArea(Area area) {
this.area = area;
}
public Policeworktime getPoliceworktime() {
return this.policeworktime;
}
public void setPoliceworktime(Policeworktime policeworktime) {
this.policeworktime = policeworktime;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
}
这是我的角色实体:
@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;
@Column(name="role_name", length=45)
private String roleName;
//bi-directional many-to-one association to User
@OneToMany(mappedBy="role", cascade={CascadeType.ALL})
private List<User> users;
public Role() {
}
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public User addUser(User user) {
getUsers().add(user);
user.setRole(this);
return user;
}
public User removeUser(User user) {
getUsers().remove(user);
user.setRole(null);
return user;
}
}
您不需要创建 Colunm roleId。您只需将关系与表格放在一起。例如,在我的情况下,我有一个具有角色的 OneToMany 用户。我只在我的 MySql 数据库中建立了关系。然后,您可以创建自己的实体或随意使用 JPA 工具。用户实体有一个对象Role,Role实体有一个List。
@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;
@Column(name="role_name", length=45)
private String roleName;
//bi-directional many-to-one association to User
@OneToMany(mappedBy="role")
private List<User> users;
public Role() {
}
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public User addUser(User user) {
getUsers().add(user);
user.setRole(this);
return user;
}
public User removeUser(User user) {
getUsers().remove(user);
user.setRole(null);
return user;
}
}
@Entity
@Table(name = "user")
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
// bi-directional many-to-one association to Role
@ManyToOne
@JoinColumn(name = "role_role_id", nullable = false)
private Role role;
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
}