hibernate---->多对一关联映射
1、多对一关联映射
<many-to-one>会在多的一端加入一个外键,指向一的一端(主键),这个外键列名是由<many-to-one>中的column属性定义的,如果忽略了这个属性那么默认的外键与实体的属性一致
功能:
a. 告诉数据库,多的一端有一个外键,参照一的一端主键.
b. 告诉hibernate,在插入多的一端时,外键的插入会参照一的一端的主键.
c. 告诉hibernate,在查找多的一端时,会自动查找一的一端的对象(多的一端外键 ---> 一的一端主键)
2、cascade级联 -- 是对象的连锁操作
* <many-to-one name="group" column="groupid" cascade="all"/>
* cascade取值为: all, none, save-update, delete -- 在各种情况下的级联操作.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.wsz.entity.User" table="t_user"> <id name="id"> <generator class="native" /> </id> <property name="name" /> <many-to-one name="group" column="groupid" cascade="all"/> </class> </hibernate-mapping>
user.java
package com.wsz.entity; public class User { private int id; private String name; private Group group ; 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 Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } }
group.java
publicclass Group { privte String id; private String name; } publicclass User{ private String id; privte String name; private Group group; public Group getGroup(){return group;} public void setGroup(Group group){ this.group = group; }级联添加
package com.wsz.test; import junit.framework.TestCase; import org.hibernate.Session; import com.wsz.entity.Group; import com.wsz.entity.HibernateUtils; import com.wsz.entity.User; public class TestManyToOne extends TestCase { public void testManyToOne() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction(); Group group = new Group(); group.setName("CEIT"); for (int i = 0; i < 10; i++) { User user = new User(); user.setName("第" + i + "个"); user.setGroup(group); session.save(user); } session.getTransaction().commit(); User user = (User) session.load(User.class, 27); System.out.println(user.getGroup().getName()); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } finally { HibernateUtils.closeSession(session); } } }