hibernate多对一映射

来源:互联网 发布:淘宝和卷皮哪个更好 编辑:程序博客网 时间:2024/04/30 17:23
 

Employ(员工):  Integer id; String name; Department department;

Department(部门):Integer id; String name;

Employ.hbm.xml:

<hibernate-mapping package="employ所在的报名">

  <class  name="Employ" table="emplytable">

<id>

<generator class="native">  <!-- 主键生成策略 -->

</id>

<property  name="name" column="name"/> <!-- 普通属性 -->

<many-to-one  name="department" column="departId"/> <!-- 默认参照关联表的主键,完成由对象模型向关系模型的转化,property-ref 指定参照非关联表主键 -->

  </class>

</hibernate-mapping>

Depatrment.hbm.xml:

<hibernate-mapping package="department所在的报名">

<class name="Department" table="department">

<id>

<generator class="native"/>

</id>

<property name="name" column="name"/>

</class>

</hibernate-mapping>

 

多对一查询测试:

public void save(Objec o){

Session session=HibernateUtil.getSession();  //获得session

Transaction tx=null;

try{

   tx=session.beginTransaction( );

  session.save(o);

  tx.commit( );

}catch(HibernateException e){

if(tx!=null){

tx.rollback( );//事务回滚

}

throw e;

}finally{

if(session!=null)

session.close( );

}

public  Employee get(integer id)

{

    Session session=null;

    Employee employee=null;

   try{

    session=HibernateUtil.getSession( );

    employee= session.get(Employee.class,id)

    return employee;

  }catch(HibernateException e){

throw e;

}finally{

if(session!=null)

session.close( );

}

return null;

}

public static void main(String[ ] args)

{

  Department depart=new Department( );

 depart.setName("depart");

Employee employee=new Employee( );

employee.setName("employ");

employee.setDepartment(depart);    //在对象模型上建立员工和部门之间的关联

save(depart);//存储部门

save(employee);//存储员工

 

//若存储顺序改为如下,将差生一条额外的更新语句

save(employee); //此时存储的员工没有部门信息

save(depart);  //存储部门,此时将产生一条更新语句,跟新员工表中部门的信息(因为刚存储的员工是持久态对象,hibernate会检测起属性变化而作更新处理)

}