thinkGhoster的专栏

---泥搅水来水和泥---

Hibernate多对一单向关联映射

     Hibernate多对一单向关联映射 

1、AddressTwo.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping 
          PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" 
>
<hibernate-mapping>
  
<class name="com.persistent.AddressTwo" table="address">  
    
<id name="id" column="addressId" unsaved-value="0">
        
<generator class="increment">
        
</generator>
    
</id>    
    
<property name="addressName" column="addressName"></property>    
    
<many-to-one name="peopleTwo" 
                 column
="peopleId" 
                 class
="com.persistent.PeopleTwo"
                 cascade
="all"
                 
>
    
</many-to-one>    
  
</class>  
</hibernate-mapping>

2、PeopleTwo.hbm.xml

<hibernate-mapping  default-lazy="false">  
   
<class name="com.persistent.PeopleTwo" table="people">     
     
<id name="id" column="peopleId" unsaved-value="0">    
        
<generator class="increment">        
        
</generator>    
     
</id>     
     
<property name="name" column="name"></property>          
   
</class>
</hibernate-mapping>

3、PeopleTwo.java和AddressTwo.java

public class PeopleTwo ...{    
    
private long id;
    
private String name;
    …
}

public class AddressTwo ...{    
    
private long id;
    
private PeopleTwo peopleTwo;
    
private String addressName;

}

4、测试程序

Session session = HibernateSessionFactory.getSession();
session.beginTransaction();
List result 
= session.createQuery("from AddressTwo").list();
session.getTransaction().commit();
for(int i = 0; i<result.size(); i++)...{
       AddressTwo addressTwo 
= (AddressTwo)result.get(i);
       System.out.println(addressTwo.getId()
+"    "
                                            +addressTwo.getAddressName()+"    "
                                            +addressTwo.getPeopleTwo().getId()+"     "
                                            +addressTwo.getPeopleTwo().getName()
                                        );
}
  
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭