칠일대다 관계 부서와 직원의 관계

3543 단어 일대다
                         
                        

   
package vo.util.bean;

import java.util.Set;

/**
 *    
 * @author Administrator
 *
 */
public class Department {
  private int id;
  private String name;
  //   Set               
  private Set<Employee> ems;
public int getId() {
	return id;
}
public Set<Employee> getEms() {
	return ems;
}
public void setEms(Set<Employee> ems) {
	this.ems = ems;
}
public void setId(int id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
}

      
<?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="vo.util.bean">

	<class name="Department">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name"/>
		<!--             -->
		<set name="ems">
		<!--          -->
		<key column="depaer_id"/>
		   <!--            -->
		  <one-to-many  class="Employee" />
		</set>
	</class>
	
</hibernate-mapping>

  

package vo.util.test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import vo.util.HibernateUtil;
import vo.util.bean.Department;
import vo.util.bean.Employee;

public class OneToMany {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
         add();
        query(1);
	}
    static Department add(){
    	Session session = null;
    	Transaction tx = null;
    	try{
    		session =HibernateUtil.getSession();
    		tx = session.beginTransaction();
    		//…    save,delete,update,get…
    		Department dpart=new Department();
    		dpart.setName("     ");
    		
    		Employee em1=new Employee();
    		em1.setName("     ");
    		em1.setDerpartment(dpart);
    		
    		Employee em2=new Employee();
    		em2.setName("     ");
    		em2.setDerpartment(dpart);
    		session.save(dpart);
    		session.save(em1);
    		session.save(em2);
    		
    		
    		tx.commit();
    		return dpart;
    	}finally{
    		if(session != null)session.close();
    	} 

    }
    
    static Department query(int id){
    	Session session=null;
    	
    	try{
    	   session=HibernateUtil.getSession();
    	   Department d=(Department)session.get(Department.class, id);
    	   
    	   System.out.println(d.getName()+"--------->"+d.getEms().size());
    	  
    		return d;
    	}finally{
    		if(session != null)session.close();
    	} 

    }
}


   :                    Set<>           
          <set> <key> <one-to-many>         

end   !

좋은 웹페이지 즐겨찾기