首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Hibernate多对1

2012-09-10 
Hibernate多对一?Many:package com.domainpublic class Employee {private int idprivate String namep

Hibernate多对一

?Many:

package com.domain;public class Employee {private int id;private String name;private Department depart;}

?

One:

package com.domain;public class Department {private int id;private String name;}

?

Employee.hbm.xml:

<?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 package="com.domain"><class name="Employee" discriminator-value="0"><id name="id"><generator /></id><property name="name" unique="true" /><many-to-one name="depart" column="depart_id" /></class></hibernate-mapping>

?

Department.hbm.xml:

<?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 package="com.domain"><class name="Department"><id name="id"><generator /></id><property name="name" /></class></hibernate-mapping>

?

?Many2One:

import org.hibernate.Session;import org.hibernate.Transaction;import com.dao.HibernateUitl;import com.domain.Department;import com.domain.Employee;public class Many2One {public static void main(String[] args) {add();}static Department add() {Session s = null;Transaction tx = null;try {Department depart = new Department();depart.setName("depart name");Employee emp = new Employee();emp.setDepart(depart);// 对象模型:建立两个对象的关联emp.setName("emp name");s = HibernateUitl.getSession();tx = s.beginTransaction();s.save(depart);s.save(emp);tx.commit();return depart;} finally {if (s != null)s.close();}}}

?

?

热点排行