繁体   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