Hibernate复合ID合并 [英] Hibernate composite id merge

查看:62
本文介绍了Hibernate复合ID合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Hibernate与JPA一起使用,并且具有这样的关系:

I'm using Hibernate with JPA and have a relation like this:

@Entity
@Table(name = "first")
public class First {
...
@OneToMany(mappedBy = "first")
private List<Availability> availabilities;
...
}


@Entity
@Table(name = "second")
public class Second {
...
@OneToMany(mappedBy = "second")
private List<Availability> availabilities;
...
}

@Entity
@Table(name="availability")
public class Availability implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "first_id")
private First first;

@Id
@ManyToOne
@JoinColumn(name = "second_id")
private Second second;

@Column(name = "availability")
private Integer availability;

...
hashcode and equals
}

我想分别管理这3个实体.第一和第二工作正常,但是当我尝试merge()时,第三个postgresql获得一个空值而不是id,并且抛出了违反约束的异常.为什么?甚至可以在该实体上使用合并功能向表中添加新行吗?

I want to manage these 3 entities separately. First and Second work fine, but when I try to merge() the third one postgresql gets a null value instead of the id's and constraint violation exception is thrown. Why? Can I even use merge on this entity to add new rows to the table?

更新:合并是这样的:

public Availability setAvailability(Availability a) {
return em.merge(a);
}

从前端开始反序列化可用性(仅提及,其中分离了关键"类的集合).

where the availability is deserialized from front-end (just to mention, the collections of "key" classes are detached in it).

推荐答案

我通过避免使用Composite ID解决了该问题.重新思考问题后,我发现这种情况下我实际上可以使用唯一约束.

I solved the problem by avoiding the use of Composite ID. After rethinking the problem I found out that this case I actually can use an unique constraint.

@Entity
@Table(name = "availabilities", uniqueConstraints = { @UniqueConstraint(columnNames = {
    "first_id", "second_id" }) })
@SequenceGenerator(initialValue = 1, name = "availabilities_sequence", sequenceName =     "availabilities_sequence")
public class Availability implements IAvailability, Serializable {

private static final long serialVersionUID = -2977047920673617888L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "availabilities_sequence")
@Column(name = "id")
private Integer id;

@ManyToOne
@JoinColumn(name = "first_id", nullable=false)
private First first;

@ManyToOne
@JoinColumn(name = "second_id", nullable=false)
private Second second;

@Column(name = "availability", nullable=false)
private Integer availability;

...
}

这篇关于Hibernate复合ID合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆