简体   繁体   中英

How to auto insert foreign key when insert entity/object by Spring Boot JPA to MySQL

I tried to insert an entity that contains foreign key from Spring boot JPA to MYSQL. But get error:

java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.

I know it is an error when I insert null into a column that does not allow null. I know the fix(please see myMainController below) is get object Role (foreignkey) to set into my User object then insert User Object to DB (new row in DB) (the necessary data of Role is already in the DB). But I want when I insert User, it will auto insert Object Role because I have set the realtion clearly(more info please see my pictures in User Entity and Role Entity). Please see my Code.

This is ERR:

java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.

This is 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;
}

}

This is my User Entity:

@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;
}

}

This is my Role Entity:

@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;
    }

}

You don't need to create Colunm roleId. You just put relational with tables. For example in my situation, I have OneToMany User with Role. I only established relational in my MySql DB. And then, you can create your own entities or use the JPA tool at your disposal. User entity has a object Role, Role entity has a 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;
}



}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM