hibernate 的一对多关系有三种:1对n n对1 1对1
其中一对多关系在现实生活中还是比较普遍的,例如:学生和班级,人和地址,客户和订单等等
其实我个人认为一对多的关系有点像将集合映射,这个集合映射是有两个po文件组成,一个po是多一个po是一
代码如下:
首先创建一个主要po文件(person文件)
package one;
import java.util.HashSet;
import java.util.Set;
public class person {
private int id;
private String name;
private Set<String> address=new HashSet<String>();
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 Set<String> getAddress() {
return address;
}
public void setAddress(Set<String> address) {
this.address = address;
}
}
其次再创建另一个辅助po文件(address文件)
package one;
public class address {
private int addressid;
private String addressname;
private person person;
public int getAddressid() {
return addressid;
}
public void setAddressid(int addressid) {
this.addressid = addressid;
}
public String getAddressname() {
return addressname;
}
public void setAddressname(String addressname) {
this.addressname = addressname;
}
public person getPerson() {
return person;
}
public void setPerson(person person) {
this.person = person;
}
}
两个po文件的配置
person配置
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="one">
<class name="person" table="person">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" column="name"></property>
<set name="address">
<key column="address_id"></key>
<one-to-many class="address"/>
</set>
</class>
</hibernate-mapping>
address配置
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="one">
<class name="address" table="address">
<id name="addressid" column="addressid">
<generator class="native"/>
</id>
<property name="addressname" column="addressname"></property>
<many-to-one name="person" class="person" column="address_id"></many-to-one>
</class>
</hibernate-mapping>
运行类:
package one;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.junit.Test;
public class app {
static SessionFactory sf;
static{
sf=new Configuration().configure().buildSessionFactory();
}
@Test
public void test_add() {
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
person p = new person();
p.setName("林先生");
//林先生的第一个地址
address ad = new address();
ad.setAddressname("东莞");
ad.setPerson(p);
//林先生的第二地址
address ad1=new address();
ad1.setAddressname("道滘");
ad1.setPerson(p);
session.save(ad1);
session.save(ad);
session.save(p);
tx.commit();
session.close();
}
}
运行效果如下