hibernate<2>-----多对一
Department.java
hibernate.cfg.xmlpackage 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();}}}