0

As I know about designing of REST-API's in SpringBoot we will design API's for User like

  1. For ADD User = /v1/users (Add a single object into a user collection)

  2. For GET/UPDATE/DELETE user = /v1/users/{userId} (for get/update/delete a single object from users collection)

Now We also design an API's for User Address like

  1. For Add Address = /v1/users/{userId}/addresses (Add a single object into addresses of user followed by userId)

  2. For GET/UPDATE/DELETE = /v1/users/{userId}/addresses/{addressId} (get/update /delete of address from addresses for a user of given userId)

So, I have created API's like this but for add/get/update/delete I can direct addresses into Address table via RestController -> Services -> Repository -> DB

Now for Address CRUD I'm never used {userId} which is provided in API

Sample for Add/Update address

@Override
public Address addAddress(Address address) {

    address = addressRepository.save(address);
    return address;
}

Is there I'm doing something wrong in code or my concept about rest is not cleared.

Thank you in advance.

1 Answers1

0
  1. I think first you should come up with the structure of relationship between user and address.
  2. Like ADDRESS CANT EXISTS WITHOUT USER and USER CAN HAVE MANY ADDRESSES or CAN HAVE ONLY ONE ADDRESS that is basically the cardinality of the relationship. See the accepted anwer.
  3. Once that done and you come up with the CASCADE TYPE and USE THE HELPER method persist the parent along with child. Here is the good example. Will try to upload code for your example. Let me know of this:)

EDIT:

@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.
   }
}
DevApp
  • 55
  • 1
  • 7