数据库表结构如下:
id INT
extId VARCHAR
name VARCHAR
parent INT (references self.id)
这是实体
@Entity
@Table(name = "categories")
public class Category
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@ManyToOne
@JoinColumn(name = "parent", referencedColumnName = "id")
private Category parent;
@org.hibernate.annotations.OrderBy(clause = "name ASC")
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", cascade = CascadeType.ALL)
private Set<Category> children = new HashSet<>();
@Column(name = "extId")
private String extId;
@Column(name = "name")
private String name;
public void addChild(Category child)
{
child.setParent(this);
this.children.add(child);
}
//getters and setters ...
}
一开始只有一个实体:
{
id: 0
extId: ''
name: 'Category'
parent: null
children: Set<Category>{/*empty*/}
}
此实体在程序开头被提取并分配给另一个类
稍后此类将新Category
作为子项添加到现有根(在开头提取的属性)属性
小孩的加法是这样做的:
Session session = HibernateSessionFactory.getInstance().getFactory().openSession();
//gather data
Category child = new Category();
//set name
//set extId
this.rootCategory.addChild(child);
Transaction tx = session.beginTransaction();
session.save(this.rootCategory);
tx.commit();
session.close();
在此之后而不是数据库中的预期结果:
Root(id(0), extId(''), parent(null), name('root'))
\-— Child(id(10), extId('art-0'), parent(0), name('child'))
我得到以下结果
Root(id(0), extId(''), parent(null), name('root'));
Root(id(10), extId(''), parent(null), name('root'))
\-— Child(id(11), extId('art-0'), parent(10), name('child'))
备注:
Session
,此会话通过Singleton SessionFactory
refresh()
root实体 - 一切正常,没有重复这种行为可能是什么原因(假设两个不同的会话)?它怎么能修复?