[原创]hibernate 一对一实践 by hjack[5]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

2)、新建Test类,用于测试。
    /*
     * 创建日期 2005-8-10
     *
     * 更改所生成文件模板为
     * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
     */
    package test;
   
    import model.Author;
    import model.Topic;
    import net.sf.hibernate.HibernateException;
    import net.sf.hibernate.Session;
    import net.sf.hibernate.Transaction;
   
    /**
     * @author hjack
    
     * 更改所生成类型注释的模板为
     * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
     */
    public class Test {
   
     Session sess;
     Transaction tx;
     
     public void insertTopic(Topic topic,int userID) throws HibernateException{
      try{
       sess = HibernateUtil.currentSession();
       tx = sess.beginTransaction();
       //新建一个author对象,并把作者id置入该对象里。   
       Author author = new Author();
       author.setId(userID);   
       //新建一个topic对象,设置用户名和把author对象set进去。
       topic.setAuthor(author);
       //因为只是插入一个话题,并不必在author表中插入一条记录,所以只需save(topic)   
       sess.save(topic);
       tx.commit();
      }catch(HibernateException e){
       System.out.println(e.toString());
      }finally{
       if(tx!=null){
        tx.rollback();
       }
       HibernateUtil.closeSession();
      }
     }
     
     public void insertAuthor(Author author) throws HibernateException{
      try{
       sess = HibernateUtil.currentSession();
       tx = sess.beginTransaction();
       sess.save(author);
       tx.commit();
      }catch(HibernateException e){
       System.out.println(e.toString());
      }finally{
       if(tx!=null){
        tx.rollback();
       }
       HibernateUtil.closeSession();
      }
     }
   
   
     public Topic query(int id) throws HibernateException{
      Topic topic = null;
      try{
       sess = HibernateUtil.currentSession();   
       topic=(Topic)sess.load(Topic.class,new Integer(id));   
      }catch(HibernateException e){
       e.printStackTrace();
      }finally{
       HibernateUtil.closeSession();
      }
      return topic;
     }
     
     public static void main(String[] args) {
      
      Test app = new Test();
      try {
       /*测试插入作者
       Author author = new Author();
       author.setName("jack");
       app.insertAuthor(author);
       */
       /*测试插入主题
       Topic topic = new Topic();
       topic.setName("helloworld.");
       app.insertTopic(topic,1

本文关键:[原创]hibernate 一对一实践 by hjack
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top