如何在mySql数据库中保存对象?

时间:2017-09-30 15:36:45

标签: java mysql spring-boot

我在数据库中保存对象时遇到问题,错误是:无法执行语句;

SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

和代码是

@RequestMapping( value = "/saveeeee", method = RequestMethod.POST)
 public ModelAndView doSave(
   @RequestParam("user_id") String user_id, 
   @RequestParam("username") String username,
   @RequestParam("password") String password,
   @RequestParam("rol") String rol){
     ModelAndView mv = new ModelAndView("redirect:/utilisateurs");
     User op;
     op = new User();

     Role ro;
     ro = new Role();

     ro.setRole(rol);
     ro.setUsername(username);


     if(!user_id.isEmpty()){
         op =(User)appRepo.findOne(Integer.parseInt(user_id));
     } else {
         op = new User();
     }

     op.setUsername(username);
     op.setPassword(passwordEncoder.encode(password));
     op.setRo(ro);

     appRepo.save(op);
     return mv;
  }

1 个答案:

答案 0 :(得分:0)

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(stat_tnuser_roles,CONSTRAINT fk_username FOREIGN KEY( username)参考usersusername))