java如何使用相关的自动递增ID保存具有OneToMany关系的实体
我试图保存一个“用户”对象,该对象通过一个OneToMany关系与一个“志愿者”对象相关联
当我试图保存它时,它只在我为这两个对象提供主ID时才起作用。但是,我需要的是保存实体,并让数据库通过自动增量指定ID。我不知道我该怎么做,甚至不知道这是否可能
工作正常的Json映射:
{
"id":8,
"userName": "user8",
"password": "pass1234",
"volunteersId": 6,
"volunteers": [{
"id":6,
"committeesId": 2,
"outreachDate": "2019-12-07",
"usersId": 8
}]
}
我需要的Json映射(但不起作用):
{
"userName": "user8",
"password": "pass1234",
"volunteersId": 6,
"volunteers": [{
"committeesId": 2,
"outreachDate": "2019-12-07",
}]
}
所以我在想,也许有一种方法可以连接外键,这样我就不必显式地添加自动增量ID(usersId,autologsid)
用户控制器:
@Controller
public class UserController {
@RequestMapping(value = "/v1/users", method = RequestMethod.POST)
public ResponseEntity<Object> saveUsers( @RequestBody UserEntity request){
try {
return ResponseEntity.ok(userService.saveUser(request));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
用户服务:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<UserEntity> saveUser(UserEntity user){
userRepository.save(user);
Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());
return userRepository.findAll(pageable);
}
}
用户存储库:
public interface UserRepository extends JpaRepository<UserEntity, Long> {
public List<UserEntity> findAllByOrderByIdAsc();
public List<UserEntity> findAllByOrderByIdDesc();
public Page<UserEntity> findByUserNameContaining(String userName, Pageable pageable);
}
用户实体:
@Entity
@Table(name = "users")
public class UserEntity {
@Id
private long id;
@Column(name = "username")
private String userName;
private String password;
@Column(name = "volunteers_id", nullable = true)
private Long volunteersId;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "users_id")
private List<VolunteerEntity> volunteers = new ArrayList<>();
// omitted getters and setters
}
志愿者实体:
@Entity
@Table(name = "volunteers")
public class VolunteerEntity {
@Id
private long id;
@Column(name = "committees_id")
private long committeesId;
@Column(name = "outreach_date")
private Date outreachDate;
@Column(name = "users_id")
private Long usersId;
// omitted getters and setters
}
对如何拯救整个实体有什么想法或建议?我想知道这是否真的可以保存为一个完整的过程。虽然如果没有,我正在考虑独立保存它们(先保存用户信息,然后再保存志愿者信息),但万一可能的话,这确实是一个很大的帮助
# 1 楼答案
您需要在@id旁边添加@GeneratedValue站
在顺序的情况下,您需要添加一个额外的涂鸦
# 2 楼答案
这将使主id自动生成