首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

hibernate<2>多对1

2012-09-23 
hibernate2-----多对一Department.javahibernate.cfg.xmlpackage cn.anycall.hibernateimport org.hibe

hibernate<2>-----多对一
Department.java



hibernate.cfg.xml
package cn.anycall.hibernate;import org.hibernate.Hibernate;import org.hibernate.Session;import org.hibernate.Transaction;import cn.anycall.hibernate.domain.Department;import cn.anycall.hibernate.domain.Employee;public class Many2One {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubDepartment depart = add();System.out.println(depart.getName());Employee emp = queryE(1);System.out.println(emp.getDepart().getName());}static Department add(){Session s = null;Transaction tx = null;try{s = HibernateUtil.getSession();tx = s.beginTransaction();Department depart = new Department();depart.setName("depart name");Employee emp = new Employee();emp.setDepart(depart);emp.setName("employee name");s.save(depart);s.save(emp);tx.commit();System.out.println("end");return depart;}finally{if(s!=null)s.close();}}static Department query(int id){Session s = null;try{s = HibernateUtil.getSession();Department depart = (Department) s.get(Department.class, id);System.out.println("end");return depart;}finally{if(s!=null)s.close();}}static Employee queryE(int id){Session s = null;try{s = HibernateUtil.getSession();Employee employ = (Employee) s.get(Employee.class, id);System.out.println(employ.getDepart().getName());Hibernate.initialize(employ.getDepart());System.out.println("end");return employ;}finally{if(s!=null)s.close();}}}

热点排行