Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring Boot JPA向MySQL插入实体/对象时如何自动插入外键_Java_Mysql_Spring Boot_Foreign Keys_Relational Database - Fatal编程技术网

Java Spring Boot JPA向MySQL插入实体/对象时如何自动插入外键

Java Spring Boot JPA向MySQL插入实体/对象时如何自动插入外键,java,mysql,spring-boot,foreign-keys,relational-database,Java,Mysql,Spring Boot,Foreign Keys,Relational Database,我试图将一个包含Spring boot JPA外键的实体插入MYSQL。但是得到错误: java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null. 我知道在不允许null的列中插入null是错误的。我知道修复程序(请参见下面的myMainController)是获取要设置到我的用户对象中的对象角色(foreignkey),然后将用户对象插入到DB(DB中的新行)(角色的必要数据

我试图将一个包含Spring boot JPA外键的实体插入MYSQL。但是得到错误:

java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.
我知道在不允许null的列中插入null是错误的。我知道修复程序(请参见下面的myMainController)是获取要设置到我的用户对象中的对象角色(foreignkey),然后将用户对象插入到DB(DB中的新行)(角色的必要数据已经在DB中)。但我想当我插入用户时,它会自动插入对象角色,因为我已经清楚地设置了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;
}
@实体
@表(name=“user”)
@NamedQuery(name=“User.findAll”,query=“从用户u中选择u”)
公共类用户实现可序列化{
私有静态最终长serialVersionUID=1L;
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(name=“user\u id”,unique=true,nullable=false)
私有整数用户标识;
@列(长度=1000)
私有字符串地址;
@列(name=“area\u id”)
私有整数区域ID;
@列(name=“back\u id\u card\u img”,长度=200)
私有字符串backidmg;
@列(name=“font\u id\u card\u img”,长度=200)
私有字符串fontIdCardImg;
@柱(长度=45)
私有字符串全名;
@柱(长度=45)
私有字符串密码;
@柱(长度=45)
私有字符串电话号码;
@列(name=“role\u id”)
私有整数roleId;
//事故的双向多对一关联
@OneToMany(mappedBy=“用户”)
私人名单事故;
//双向多对一关联到区域
@许多酮
@JoinColumn(name=“area\u area\u id”)
私人区域;
//与policyWorkTime的双向多对一关联
@许多酮
@JoinColumn(name=“policworktime\u police\u user\u id”)
私人警察工作时间警察工作时间;
//双向多对一关联到角色
@manytone(cascade={CascadeType.ALL})
@JoinColumn(name=“role\u role\u id”,nullable=false)
私人角色;
公共用户(){
}
公共整数getUserId(){
返回this.userId;
}
public void setUserId(整数userId){
this.userId=userId;
}
公共字符串getAddress(){
返回此地址;
}
公共无效设置地址(字符串地址){
this.address=地址;
}
公共整数getAreaId(){
返回此.areaId;
}
公共void setAreaId(整数areaId){
this.areaId=areaId;
}
公共字符串getBackIdCardImg(){
返回此.backIDmg;
}
public void setBackIdCardImg(字符串backIdCardImg){
this.backIdCardImg=backIdCardImg;
}
公共字符串getFontIdCardImg(){
返回此.fontIdCardImg;
}
public void setFontIdCardImg(字符串fontIdCardImg){
this.fontIdCardImg=fontIdCardImg;
}
公共字符串getFullname(){
返回this.fullname;
}
public void setFullname(字符串fullname){
this.fullname=fullname;
}
公共字符串getPassword(){
返回此密码;
}
public void setPassword(字符串密码){
this.password=密码;
}
公共字符串getPhonenumber(){
返回此.phonenumber;
}
public void setPhonenumber(字符串phonenumber){
this.phonenumber=电话号码;
}
公共整数getRoleId(){
返回此.roleId;
}
公共void setRoleId(整数roleId){
this.roleId=roleId;
}
公共交通意外名单({
把这个还给我;
}
公共交通事故(列出事故){
这就是事故;
}
公共事故(意外事故){
获取事故()。添加(事故);
事故。设置用户(本);
返回事故;
}
公共事故排除事故(事故){
获取事故()移除(事故);
意外。setUser(空);
返回事故;
}
公共区域{
返回此区域;
}
公共空地设置区(面积){
这个面积=面积;
}
公共policyWorkTime GetPolicyWorkTime(){
返回此.policworktime;
}
public void setpolicworktime(policworktime policworktime){
this.policyWorkTime=policyWorkTime;
}
公共角色getRole(){
返回这个角色;
}
public void setRole(角色角色){
this.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;
    }

}
@实体
@表(name=“role”)
@NamedQuery(name=“Role.findAll”,query=“从角色r中选择r”)
公共类角色实现可序列化{
私有静态最终长serialVersionUID=1L;
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(name=“role\u id”,unique=true,nullable=false)
私有整数roleId;
@列(name=“role\u name”,长度=45)
私有字符串roleName;
//对用户的双向多对一关联
@OneToMany(mappedBy=“role”,cascade={CascadeType.ALL})
私人名单用户;
公共角色(){
}
公共整数getRoleId(){
返回此.roleId;
}
公共void setRoleId(整数roleId){
this.roleId=roleId;
}
公共字符串getRoleName(){
返回此.roleName;
}
public void setRoleName(字符串roleName){
this.roleName=roleName;
}
公共列表getUsers(){
将此文件返回给用户;
}
公共用户(列表用户){
this.users=用户;
}
公共用户addUser(用户用户){
getUsers().add(用户);
user.setRole(this);
返回用户;
}
公共用户removeUser(用户用户){
getUsers().remove(用户);
user.setRole(空);
返回用户;
}
}

您不需要创建Colunm roleId。您只需将关系表放在表中。例如,在我的情况下,我有一个具有角色的OMANY用户。我只在MySql数据库中建立了关系数据库。然后,您可以创建自己的实体或使用JPA工具。用户实体具有对象角色,角色实体具有列表

@实体
@表(name=“role”)
@NamedQuery(name=“Role.findAll”,query=“从角色r中选择r”)
公共类角色实现可序列化{
私有静态最终长serialVersionUID=1L;
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(name=“role\u id”,unique=true,nullable=false)
私有整数roleId;
@列(name=“role\u name”,长度=45)
私有字符串roleName;
//双向ma
@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;
}



}