waysun一路阳光

不轻易服输,不轻言放弃.--心是梦的舞台,心有多大,舞台有多大。踏踏实实做事,认认真真做人。

  BlogJava :: 首页 :: 新随笔 :: 联系 ::  :: 管理 ::
  167 随笔 :: 1 文章 :: 64 评论 :: 0 Trackbacks

在具体的项目应用中,我们很少会用到一对一的级联操作,且很多时候一对一的操作可以通过多对一实现,但是一对一有自己的好处,就是在任何时候都能保证主外键数据的一致性,但是多对一的情况下未必能做到.
我在项目中具体用到了一对一的级联操作,从网上拿了 一个例子来做,但是没有成功,于是只好自己研究,现在把修改后的代码帖出来.
本例子使用hibernate3.jar+oracle数据库
库表:
CARD_TEST(CARDID[NUMBER(18)],CARDNUM[VARCHAR2(20)])
USER_TEST(USERID[NUMBER(18)],USERNAME[VARCHAR2(20)])
TestMain.java

package com.gpdi.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestMain {
/**
 * 存储一个用户
 * @param user
 */
public void save(User user){
 user.setUsername("TEST");
 Card card=new Card();
 //Card card1=new Card();
 card.setCardnum("HGJUYT");
 //card1.setCardnum("fghy55");
 user.setCard(card);
 //user.setCard(card1);
 Session session=HibernateSessionFactory.currentSession();
    card.setUser(user);
    //card1.setUser(user);
 Transaction tr=session.beginTransaction();
 session.save(user);
 //session.save(card);
 tr.commit();
 session.close(); 
}

 public static void main(String[] args) throws Exception {
  TestMain test=new TestMain();
     test.save(new User());
 }

}
Card.java

package com.gpdi.test;

/**
 * Card generated by MyEclipse - Hibernate Tools
 */

public class Card  implements java.io.Serializable {
    // Fields   

     private Integer cardid;
     private String cardnum;
     private User user;

    // Constructors

    public User getUser() {
  return user;
 }
 public void setUser(User user) {
  this.user = user;
 }
 /** default constructor */
    public Card() {
    }
    /** full constructor */
    public Card(String cardnum) {
        this.cardnum = cardnum;
    }
    // Property accessors

    public Integer getCardid() {
        return this.cardid;
    }
   
    public void setCardid(Integer cardid) {
        this.cardid = cardid;
    }

    public String getCardnum() {
        return this.cardnum;
    }
   
    public void setCardnum(String cardnum) {
        this.cardnum = cardnum;
    }

}

User.java
package com.gpdi.test;

import java.util.HashSet;
import java.util.Set;

/**
 * User generated by MyEclipse - Hibernate Tools
 */

public class User  implements java.io.Serializable {
    // Fields   

     private Integer userid;
     private String username;
     private Card card;
     //private Set card = new HashSet();

    // Constructors

    public Card getCard() {
  return card;
 }

 public void setCard(Card card) {
  this.card = card;
 }

 /** default constructor */
    public User() {
    }

    /** full constructor */
    public User(String username) {
        this.username = username;
    }

    // Property accessors

    public Integer getUserid() {
        return this.userid;
    }
   
    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return this.username;
    }
   
    public void setUsername(String username) {
        this.username = username;
    }
}
HibernateSessionFactory.java

package com.gpdi.test;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html}.
 */
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * NOTICE: Location should be on the classpath as Hibernate uses
     * #resourceAsStream style lookup for its configuration file. That
     * is place the config file in a Java package - the default location
     * is the default Java package.<br><br>
     * Examples: <br>
     * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
     * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

    /** Holds a single instance of Session */
 private static final ThreadLocal threadLocal = new ThreadLocal();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static org.hibernate.SessionFactory sessionFactory;

    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

  if (session == null || !session.isOpen()) {
   if (sessionFactory == null) {
    try {
     cfg.configure(CONFIG_FILE_LOCATION);
     sessionFactory = cfg.buildSessionFactory();
    } catch (Exception e) {
     System.err
       .println("%%%% Error Creating SessionFactory %%%%");
     e.printStackTrace();
    }
   }
   session = (sessionFactory != null) ? sessionFactory.openSession()
     : null;
   threadLocal.set(session);
  }

        return session;
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     * Default constructor.
     */
    private HibernateSessionFactory() {
    }

}
Card.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    <class name="com.gpdi.test.Card" table="CARD_TEST">
 
        <id name="cardid" type="integer">
            <column name="CARDID" />
            <generator class="foreign" >
            <param name="property">user</param>
            </generator>
        </id>
        <property name="cardnum" type="string">
            <column name="CARDNUM" length="45" not-null="true" />
        </property>
        <!--
        foreign-key="userid"指定外键关联的字段,必须,不可缺少 ,cascade="save-update"指定怎么操作级联,非必须
        -->
       <one-to-one name="user" foreign-key="userid" class="com.gpdi.test.User" cascade="save-update"></one-to-one>
    </class>
</hibernate-mapping>

User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    <class name="com.gpdi.test.User" table="USER_TEST">
        <id name="userid" type="integer">
            <column name="USERID" />
            <generator class="increment"/>
        </id>
        <property name="username" type="string">
            <column name="username" length="45" not-null="true" />
        </property>
        <one-to-one name="card" foreign-key="cardid" class="com.gpdi.test.Card" cascade="save-update"></one-to-one>
        <!--
       <set name="card" inverse="true" cascade="all">
        <key column="cardid" />
        <one-to-many class="com.gpdi.test.Card" />
        </set>
         <many-to-one  name="card" class="com.gpdi.test.Card"  insert="true" unique="true" lazy="false">
         <column name="cardid"  length="18"  />
        </many-to-one>
        -->
 
    </class>
</hibernate-mapping>
Hibernate实现一对一实例源码
posted on 2008-06-18 17:41 weesun一米阳光 阅读(4585) 评论(1)  编辑  收藏 所属分类: 经典实例Hibernate

评论

# re: Hibernate实现one-to-one级联保存[自己总结] [未登录] 2008-10-15 14:17 x
骗人  回复  更多评论
  


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


网站导航: