提问人:Daniela 提问时间:4/19/2022 最后编辑:Daniela 更新时间:4/20/2022 访问量:141
在 Set 中添加 id 自动生成的对象会导致使用 Hibernate 仅添加一个元素
Add object with id autogenerated in a Set results in only adding one element by using Hibernate
问:
我想创建更多对象并将它们添加到集合中。hashcode 和 equals 方法依赖于 id(我无法更改)。
首先,每个对象都有 id=0,当尝试添加到集合中时,将导致仅添加第一个对象。
如果我在每次创建后使用 session.save(object),则该集合将包含所有元素。
问题是 id 没有创建。
你有什么解决方案吗?每次创建对象时保存内容并不容易,因为要做到这一点,我需要更改大量代码。
我从基类中添加了等号和哈希码 谢谢
public class Employee extend HibernateEntity{
public Employee(String name){
em_name = name;
}
}
//doesn't work because id=0 for both, it will add only the first one
Set set = new HashSet<Employee>();
set.add(Employee("lala"));
set.add(Employee("baba"));
works because save will provide a generated id and the object will not be the same
Set set = new HashSet<Employee>();
Employee em1 = Employee("lala");
session.save(em1);
set.add(em1);
Employee em2 = Employee("baba");
session.save(em2);
set.add(em2);
基类中的等号和哈希码:
@MappedSuperclass
public abstract class HibernateEntity extends HibernateObject implements Cloneable {
/* Primary key */
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator")
protected long id;
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof HibernateEntity)) {
return false;
}
obj = HibernateHelper.getRealObject(obj);
Object thisImpl = HibernateHelper.getRealObject(this);
if (thisImpl.getClass() != obj.getClass()) {
return false;
}
// It's now safe to cast object
final HibernateEntity other = (HibernateEntity) obj;
final HibernateEntity thisHibernteImpl = (HibernateEntity) thisImpl;
if (thisHibernteImpl.id != other.id) {
return false;
}
return true;
}
}
答: 暂无答案
评论
equals
Long