温馨提示:您的每一次转载,体现了我写此文的意义!!!烦请您在转载时注明出处http://www.blogjava.net/sxyx2008/谢谢合作!!!

雪山飞鹄

温馨提示:您的每一次转载,体现了我写此文的意义!!!烦请您在转载时注明出处http://www.blogjava.net/sxyx2008/谢谢合作!!!

BlogJava 首页 新随笔 联系 聚合 管理
  215 Posts :: 1 Stories :: 674 Comments :: 0 Trackbacks

alter table wife
        drop
        foreign key FK37AF11D67CB035

    drop table if exists husband

    drop table if exists wife

    create table husband (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )

    create table wife (
        id integer not null,
        name varchar(255),
        primary key (id)
    )

    alter table wife
        add index FK37AF11D67CB035 (id),
        add constraint FK37AF11D67CB035
        foreign key (id)
        references husband (id)

实体
Husband

private int id;
 private String name;
 private Wife wife;

Wife
private int id;
 private String name;
 private Husband husband;

Husband.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 package="com.hibernate.one2one.bean">
        
<class name="Husband" table="husband">
            
<id name="id" column="id">
                
<generator class="native"></generator>
            
</id>
            
<property name="name"></property>
            
<one-to-one name="wife" cascade="all" class="Wife"></one-to-one>
        
</class>
    
</hibernate-mapping>

Wife.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 package="com.hibernate.one2one.bean">
        
<class name="Wife" table="wife">
            
<id name="id" column="id">
                
<generator class="foreign">
                    
<param name="property">husband</param>
                
</generator>
            
</id>
            
<property name="name"></property>
            
<one-to-one name="husband" constrained="true"></one-to-one>
        
</class>
    
</hibernate-mapping>
@Test
    
public void insert(){
        Session session
=HibernateSessionFactory.getSession();
        Transaction transaction
=session.beginTransaction();
        
try {
            transaction.begin();
            Husband husband
=new Husband();
            husband.setName(
"小明");
            session.save(husband);
            Wife wife
=new Wife();
            wife.setName(
"如花");
            wife.setHusband(husband);
            session.save(wife);
            transaction.commit();
        } 
catch (HibernateException e) {
            e.printStackTrace();
            transaction.rollback();
        }
    }


示例程序
posted on 2010-10-14 10:01 雪山飞鹄 阅读(671) 评论(0)  编辑  收藏 所属分类: Hibernate

只有注册用户登录后才能发表评论。


网站导航: