据我所知,在SpringBoot中设计REST-API时,我们将为用户设计API,如
对于ADD用户= / v1 /用户 (将单个对象添加到用户集合)
对于GET / UPDATE / DELETE用户= / v1 /用户/ {userId} (对于get / update / delete 用户集合中的单个对象)
现在我们还为用户地址设计一个API,例如
对于添加地址= / v1 /用户/ {userId} /地址 (添加单个对象 进入用户地址,后跟userId)
对于GET / UPDATE / DELETE = / v1 /用户/ {userId} /地址/ {addressId} (从给定用户的地址中获取/更新/删除地址 userId)
因此,我已经创建了这样的API,但是对于添加/获取/更新/删除,我可以通过RestController-> Services-> Repository-> DB
将地址定向到Address表中现在,对于地址CRUD,我从未使用过API中提供的{userId}
添加/更新地址的示例
@Override
public Address addAddress(Address address) {
address = addressRepository.save(address);
return address;
}
我在代码中做错什么了吗,或者关于休息的概念还没有弄清。
谢谢。
答案 0 :(得分:0)
编辑:
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String userName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
private List<Address> addresses = new ArrayList<>();
public void addAddress(Address address) {
addresses.add(address);
address.setUser(this);
}
public void removeAddress(Address address) {
address.setUser(null);
this.addresses.remove(address);
}
}
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Address {
private Long id;
private String address;
@ManyToOne
private User user;
}
public class Service
{
@PostMapping(value="/saveAddressForUser")
public void saveAddressForUser(@RequestBody AddressForUser address)
{
User user=getUserFromDatabase(userId);
user.addAddress(address);
Repository.persist(user);//it will also persist address as cascade type is all.
}
}