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

Model

public class User { //多

privateIntegerid;

privateStringname;

privateGroupgroup;

}

public class Group { //一

privateIntegerid;

private String name;

}

hbm.xml

user.hbm.xml

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mappingpackage="com.model">

<classname="User"table="user1">

<idname="id"column="user_id"type="java.lang.Integer">

<generatorclass="native"/>

</id>

<propertyname="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"?>

<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mappingpackage="com.model">

<classname="Group"table="group1">

<idname="id"column="group_id"type="java.lang.Integer">

<generatorclass="native"/>

</id>

<propertyname="name"length="50"type="java.lang.String"/>

</class>

</hibernate-mapping>

操作多对一实例:

public class ManyToOneTest extends TestCase{

publicvoidtestSave1(){

Sessionsession=null;

Transactionta=null;

Useruser=null;

try{

session=HibernateUtil.getSession();

ta=session.beginTransaction();

Groupgroup=newGroup();

group.setName("php");

Useruser1=newUser();

user1.setName("菜10php");

user1.setGroup(group);

Useruser2=newUser();

user2.setName("Z3php");

user2.setGroup(group);

session.save(group);//若设cascade="all|save-update",则可无此行代码

session.save(user1);

session.save(user2);

ta.commit();

}catch(Exceptione){

e.printStackTrace();

ta.rollback();

}finally{

//关闭session,user变为detached离线对象

HibernateUtil.closeSession(session);

}

}

publicvoidtestGet1(){

Sessionsession=null;

Transactionta=null;

Useruser=null;

try{

session=HibernateUtil.getSession();

ta=session.beginTransaction();

user=(User)session.get(User.class,newInteger(3));

System.out.println("user.name="+user.getName());

System.out.println("group.name="+user.getGroup().getName());

ta.commit();

}catch(Exceptione){

e.printStackTrace();

ta.rollback();

}finally{

//关闭session,user变为detached离线对象

HibernateUtil.closeSession(session);

}

}

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

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

的取得可以是以下几种:

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

操作。它是默认值。

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

游离对象)。

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

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

相关推荐