我正在撰寫一個 spring boot 應用程式,我目前正在嘗試撰寫一個用戶注冊方法。問題是我的代碼中有一個組合:
@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
我無法擺脫這種組合,所以我的問題是:如何撰寫一個 POST 方法來注冊一個 USER,同時創建一個 Person 物件并將其保存在資料庫中?如果這有什么不同,我會使用 MySQL
uj5u.com熱心網友回復:
可能您已經創建了一個存盤庫,但我把它寫下來了。
public interface UserRepository extends JpaRepository<User, Integer> {
}
或者您可以撰寫自定義 SQL 查詢。更多的
Person person = new Person(...);
User user = new User(person, dateOfRegistration);
userRepository.save(user);
當您想要更新用戶時,它也是類似的。
User user = userRepository.getById(id);
user.setPerson(person);
userRepository.save();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/440035.html
