我有以下情况:
当我尝试将用户保存到公司时,我在数据库中的字段 company_id 为空。我不知道发生了什么!看我的json坚持用户:
{ " id":null, "姓名":"我的名字", "登录":"我的登录", "邮件":" my@mail.com" ;, "密码":"秘密&#34 ;, " federalID":" 0000000&#34 ;, "公司":{" id":1} }
我没有帖子控制器和其他类,只是显示de重要来解决这个问题。在地图使用的类下面。
用户类:
@Entity(name = "users")
@Table(name = "users")
@EqualsAndHashCode
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String login;
private String mail;
private String password;
private String federalID;
@ManyToOne(optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "company_id", referencedColumnName="company_id")
private Company company;
}
公司类:
@Entity(name="companies")
@Table(name="companies")
@EqualsAndHashCode
@Data
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String federalID;
@OneToMany(mappedBy="company", targetEntity=User.class, fetch=FetchType.EAGER)
private List<User> users;
}
其余用户实体(公司控制器遵循相同的模式):
@RestController
public class UsersController {
@Autowired
UserRepository userRepository;
@RequestMapping(value = "/user", method = RequestMethod.GET)
public List<User> getUsers(){
return userRepository.findAll();
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable("id") Long id){
return userRepository.findById(id);
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public ResponseEntity<User> createUser(@RequestBody User company){
return new ResponseEntity<>(userRepository.save(company), HttpStatus.CREATED);
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id){
userRepository.delete(id);
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
答案 0 :(得分:2)
如您所见,Company
是您User
班级的关系。由于Hibernate无法将其识别为初始化实体。
要解决此问题,您应该使用company_id手动加载公司,并且应该将加载的公司设置为User
内的UserController
类。