views:

21

answers:

1

Hi there,

I've got two entities

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;

When I create a new ServiceDownload Object and try to persists this I recieve a duplicate key exception. It seems that jpa tries to insert a new service object into the service table. How can I disable this behaviour?

A: 

You are using @GeneratedValue annotation for your @Id. According to JPA documentation, you should supply unique identifiers

By default, the application is responsible for supplying and setting entity identifiers (see @Id)

Try using a @SequenceGenerator and a sequence in your database to generate unique identifiers

hhbarriuso
@GenereatdValue must be set in my case, because I'm importing data from other databases.
asrijaal
Ok, then you should implement equals() and hashCode() to avoid inserting again retrieved instances from database
hhbarriuso