hibernate many-to-one(多对一)及 cascade(级联)

public class User { //多

private Integer id; 
private String name;
private Group group;
}

public class Group { //一

private Integer id; 
private String name;

}

hbm.xml

user.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.model">
    <class name="User" table="user1" >
        <id name="id" column="user_id" type="java.lang.Integer">
            <generator class="native" />
        </id>
        <property name="name" length="50" type="java.lang.String" />
        <many-to-one name="group" column="group_id" ></many-to-one>

<!--级联(不建议配cascade)

<many-to-one name="group" column="group_id" cascade="save-update"></many-to-one>

-->

    </class>

</hibernate-mapping>

Group.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.model">
    <class name="Group" table="group1" >
        <id name="id" column="group_id" type="java.lang.Integer">
            <generator class="native" />
        </id>
        <property name="name" length="50" type="java.lang.String" />
    </class>

</hibernate-mapping>

操作多对一实例:

public class ManyToOneTest extends TestCase{

public void testSave1(){
   Session session = null;
   Transaction ta = null;
   User user = null;
   try{
    session = HibernateUtil.getSession();
    ta = session.beginTransaction();
    Group group = new Group();
    group.setName("php");
   
    User user1 = new User();
    user1.setName("菜10php");
    user1.setGroup(group);
   
    User user2 = new User();
    user2.setName("Z3php");
    user2.setGroup(group);
   session.save(group); //若设 cascade="all|save-update" ,则可无此行代码
    session.save(user1);
    session.save(user2);
    ta.commit();
   }catch(Exception e){
    e.printStackTrace();
    ta.rollback();
   }finally{
    //关闭session, user变为detached离线对象
    HibernateUtil.closeSession(session);
   }
  
}


public void testGet1(){
   Session session = null;
   Transaction ta = null;
   User user = null;
   try{
    session = HibernateUtil.getSession();
    ta = session.beginTransaction();
    user = (User)session.get(User.class, new Integer(3));
    System.out.println("user.name=" + user.getName());
    System.out.println("group.name=" + user.getGroup().getName());
    ta.commit();
   }catch(Exception e){
    e.printStackTrace();
    ta.rollback();
   }finally{
    //关闭session, user变为detached离线对象
    HibernateUtil.closeSession(session);
   }
  
}

===================================

元素的cascade属性表明操作是否从父对象级联到被关联的对象,它

的取得可以是以下几种:

none:在保存,删除或修改当前对象时,不对其附属对象(关联对象)进行级联

操作。它是默认值。

save-update:在保存,更新当前对象时,级联保存,更新附属对象(临时对象,

游离对象)。

delete:在删除当前对象时,级联删除附属对象。

all:所有情况下均进行级联操作,即包含save-update和delete操作。

相关推荐