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试图将一个新的服务对象插入到服务表中。我怎样才能禁用这种行为?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在为 @Id 使用 @GenerateValue 注释。根据 JPA 文档,您应该提供唯一标识符
尝试使用@SequenceGenerator和数据库中的序列来生成唯一标识符
You are using @GeneratedValue annotation for your @Id. According to JPA documentation, you should supply unique identifiers
Try using a @SequenceGenerator and a sequence in your database to generate unique identifiers