使用JPA持久化PK对象(ManyToMany)

时间:2011-08-24 14:00:00

标签: java jpa persistence many-to-many

如果您知道更好的标题,请更改标题,因为我真的不知道如何表达问题。

我有三节课:

@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。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

为什么要创建一个可嵌入的UserHasContact类来存储单个整数?你让它变得比实际更难。只需使用整数ID作为联系人主键。然而,这不是您的问题的原因。

您正试图在其联系人列表中保留包含联系人的用户。您的联系人ID不会自动生成,也不会为此联系人ID分配任何ID。 JPA如何在数据库中保存此联系人?此外,你没有坚持联系,所以它是暂时的。

你必须

  • 要么为联系人分配ID,要么注释其ID以便自动生成
  • 保持联系人和用户

以下是联系人实体的代码:

@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);