2010-08-17 73 views
0

我有兩個實體JPA - 多對一級聯

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

您正在爲@Id使用@GeneratedValue註釋。根據JPA文檔,你應該提供唯一標識符

默認情況下,應用程序負責提供和設置實體標識符(請參閱@Id)

嘗試使用@SequenceGenerator,並在你的序列數據庫生成唯一的標識符

+0

@GenereatdValue必須設置在我的情況,因爲我從其他數據庫導入數據。 – onigunn 2010-08-17 12:35:49

+0

好吧,那麼你應該實現equals()和hashCode(),以避免再次從數據庫插入檢索到的實例 – hhbarriuso 2010-08-17 12:59:17