Home > Back-end >  Spring MVC - Can I create two different (associated with composition) objects in POST method
Spring MVC - Can I create two different (associated with composition) objects in POST method

Time:03-08

I'm writing a spring boot app and I'm currently trying to write an user registration method. The problem is that I have a composition in my code:

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int personID;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    // Constructor, getters and setters omitted
@Entity
public class User{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int userID;

    private LocalDate dateOfRegistration;

    @ManyToOne
    @NotNull
    private Person person; // Instance cannot exist without Person


    protected User() { }

    public User(Person person, LocalDate dateOfRegistration) {
        this.person = person; 
        this.dateOfRegistration = dateOfRegistration;
    }
    
    // Constructors, getters and setters omitted

I cannot get rid of this composition so my question is: how can I write a POST method where I'll register an USER, but also create a Person object and save it in database? I use MySQL if that makes any difference

CodePudding user response:

Probably you have already created a Repository, but I write it down.

public interface UserRepository extends JpaRepository<User, Integer> {
}

Or you can write custom SQL query. More

Person person = new Person(...);
User user = new User(person, dateOfRegistration);

userRepository.save(user);

It is similar when you want to update a user.

User user = userRepository.getById(id);
user.setPerson(person);
userRepository.save();
  • Related