Hibernate 一对多出现低级问题因为po实现了hashcode和equals方法这里设置的Id做比较
1.Hibernate中一对多的双向关联
<?xmlversion="1.0"encoding="ISO-8859-1"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classtable="T_Orgnization"name="com.love.oa.model.Orgnization">
<idname="id">
<generatorclass="native"/>
</id>
<propertyname="name"/>
<propertyname="sn"/>
<many-to-onename="parent"column="pid"/>//多对一*------1
<setname="chilren"inverse="true"cascade="all">//一对多1----*
<keycolumn="pid"/>
<one-to-manyclass="com.love.oa.model.Orgnization"/>
</set>
</class>
</hibernate-mapping>package com.love.oa.model;
import java.io.Serializable;
import java.util.Set;
/**
* @hibernate.class table="T_Orgnization"
*/
public class Orgnization implements Serializable {
/**
* @hibernate.id
* generator-class="native"
*/
private int id;
/**
* @hibernate.property
*/
private String name;
/**
* @hibernate.property
*/
private String sn;
/**
* @hibernate.many-to-one
* column="pid"
*/
private Orgnization parent;
/**
* @hibernate.set
* @hibernate.key column="pid"
* @hibernate.one-to-many class="com.love.oa.model.Orgnization"
*/
private Set chilren;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public Orgnization getParent() {
return parent;
}
public void setParent(Orgnization parent) {
this.parent = parent;
}
public Set getChilren() {
return chilren;
}
public void setChilren(Set chilren) {
this.chilren = chilren;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Orgnization other = (Orgnization) obj;
if (id != other.id)
return false;
return true;
}
}
我在测试插入数据库的时候
@SuppressWarnings("unchecked")
public void testAddOrgination() throws Exception {
Session session = baseDao.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Set hashSet = new HashSet();
Orgnization org1 = new Orgnization();
org1.setName("开发部");
org1.setSn("111");
org1.setParent(null);
Orgnization org2 = new Orgnization();
org2.setName("开发部1");
org2.setSn("222");
org2.setParent(org1);
hashSet.add(org2);
//se.save(org2);
Orgnization org3 = new Orgnization();
org3.setName("开发部2");
org3.setSn("333");
org3.setParent(org1);
//se.save(org3);
hashSet.add(org3);
System.out.println(hashSet.size());
//这里的结果始终是1,因为po实现了hashcode和equals方法这里设置的Id做比较,这里就会出现一个插入数据库的时候少一条数据,因为Set集合不能插入重复的数据,这里我要实现树状结构,所以ID是相同的,造成了插入的数据不对。悲剧了啊!真的悲剧。。。
org1.setChilren(hashSet);
session.save(org1);
transaction.commit();
session.close();
}