JPA - manytoone级联

时间:2010-08-17 12:20:56

标签: java jpa entity-relationship

我有两个实体

ServiceDownload.java

@Entity
public class ServiceDownload implements Serializable {
    private static final long serialVersionUID = -5336424090042137820L;

@Id
@GeneratedValue
private Long id;
@Length(max = 255)
private String description;

private byte[] download;

private String fileName;

@ManyToOne
private Service service;

Service.java

@Entity
public class Service implements Serializable {
    private static final long serialVersionUID = 4520872456865907866L;


@EmbeddedId
private ServiceId id;

@Length(max = 255)
private String servicename;

@Column(columnDefinition = "text")
private String highlightsText;
@Column(columnDefinition = "text")
private String detailsText;
@Column(columnDefinition = "text")
private String productText;
@Column(columnDefinition = "text")
private String dataText;

@ManyToMany(mappedBy = "services")
private Set<Machine> machines;

@OneToMany(targetEntity = ServiceDownload.class)
private List<ServiceDownload> serviceDownloads;

@OneToOne
private ServicePicture servicePicture;

当我创建一个新的ServiceDownload对象并尝试持久化时,我收到了一个重复的键异常。似乎jpa尝试将新的服务对象插入到服务表中。如何禁用此行为?

1 个答案:

答案 0 :(得分:1)

您正在为@Id使用@GeneratedValue注释。根据JPA文档,您应该提供唯一标识符

  

默认情况下,应用程序负责提供和设置实体标识符(请参阅@Id)

尝试在数据库中使用@SequenceGenerator和序列生成唯一标识符