2010-08-17 76 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