簡體   English   中英

使用JPA保持PK對象(ManyToMany)

[英]Persist PK Object with JPA (ManyToMany)

如果您知道更好的名稱,請更改標題,因為我真的不知道如何表達問題。

我有三節課:

@Entity
public class User {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "id")
 private Integer id;

 @NotNull
 @Size(min = 1, max = 45)
 @Column(name = "name")
 private String name;

 @JoinTable(name = "usuer_has_contact", joinColumns = {
     @JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {
     @JoinColumn(name = "contact_id", referencedColumnName = "id")})
 @ManyToMany(cascade = CascadeType.ALL)
 private List<Contato> contactList;

 //Getters and Setters

}

DB Table:
Table Name: User
Columns: id (int pk), name (varchar(45) not null).

@Entity
private class Contact {

 @EmbeddedId
 protected UserHasContact userHasContact;

 @NotNull
 @Size(min = 1, max = 45)
 @Column(name = "value")
 private String value;

 @ManyToMany(mappedBy = "contactList")
 private List<User> userList;

 //Getters and Setters

}

DB Table:
Table Name: Contact
Columns: id (int pk), value (varchar(45) not null).

@Embeddable
private class UserHasContact {

 @NotNull
 @Column(name = "id")
 private Integer id;

 //Getters and Setters

}

DB Table:
Table Name: UserHasContact
Columns: userId (int pk), contactId (int pk).

我想做的是,當我堅持用戶本身時,要堅持一切。 例如:

User user = new User();
user.setContactList(new ArrayList<Contact>());

Contact contact = new Contact();
contact.setValue("555-5555");

user.getContactList().add(contact);

// Here I'd call another class, passing User so it would only do a
// entityManager.persist(user), and it would persist it all and
// take care of all tables for me. What I don't want to do is to
// fill up the values myself, I want let JPA do it for me.

我希望這樣做后保存,但是它說contactId為null,不能為null。 我能做什么?

為什么要創建一個可嵌入的UserHasContact類以僅存儲一個Integer? 您正在使它變得不必要。 只需使用Integer ID作為聯系人主鍵即可。 但是,這不是問題的原因。

您試圖將包含聯系人的用戶保留在其聯系人列表中。 您的聯系人ID不會自動生成,並且您沒有為此聯系人ID分配任何ID。 JPA如何將該聯系人保存在數據庫中? 此外,您沒有保持聯系,因此是暫時的。

你必須

  • 為聯系人分配ID或注釋其ID,以便其自動生成
  • 保持聯系以及用戶

這是Contact實體的代碼:

@Entity
private class Contact {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY) // this makes the ID auto-generated
 @Column(name = "id")
 private Integer id;

 @NotNull
 @Size(min = 1, max = 45)
 @Column(name = "value")
 private String value;

 @ManyToMany(mappedBy = "contactList")
 private List<User> userList;

 //Getters and Setters
}

在創建用戶和聯系人的代碼中:

User user = new User();
user.setContactList(new ArrayList<Contact>());

entityManager.persist(user);

Contact contact = new Contact();
contact.setValue("555-5555");

entityManager.persist(contact);

user.getContactList().add(contact);
// you should also make sure that the object graph is consistent, so
// the following line should lso be added, (though not strictly necessary)
contact.getUserList().add(user);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM