我在我的webapp中使用JPA,我无法弄清楚如何持久保存两个彼此相关的新实体.这是一个例子:
+-----------------+ +--------------------+ | Consumer | | ProfilePicture | +-----------------+ +--------------------+ | id (PK) |---| consumerId (PPK+FK)| | userName | | url | +-----------------+ +--------------------+
该消费者有一个ID和其他一些价值观.该ProfilePicture使用消费者的ID,因为它是自己的主键和外键.(因为如果没有消费者,ProfilePicture将不存在,并且不是每个消费者都有ProfilePicture)
我使用NetBeans生成实体类和会话bean(外观).
Consumer.java
@Entity
@Table(name = "Consumer")
@NamedQueries({...})
public class Consumer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "userName")
private String userName; …Run Code Online (Sandbox Code Playgroud)