SSH框架搭建过程---之Hibernate框架的使用(1)

Hibernate框架的使用

0.导包

1. hibernate.cfg.xml

         

<span style="font-size:12px;color:#339999;"><strong><?xml version="1.0"encoding="UTF-8"?>
         <!DOCTYPE hibernate-configurationPUBLIC
                            "-//Hibernate/HibernateConfiguration DTD 3.0//EN"
                            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
                           
         <hibernate-configuration>
 
                   <session-factory>
 
                            <!-- Databaseconnection settings -->
                            <propertyname="connection.driver_class">com.mysql.jdbc.Driver</property>
                            <property name="connection.url">jdbc:mysql://localhost:3306/graduate</property>
                            <propertyname="connection.username">root</property>
                            <propertyname="connection.password">root</property>
 
                            <!-- SQL dialect-->
                            <propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>
 
                            <!-- Echo allexecuted SQL to stdout -->
                            <propertyname="show_sql">true</property>
                            <propertyname="format_sql">true</property>
 
                            <mappingresource="cn/edu/bucea/domain/Demo.hbm.xml" />
 
                   </session-factory>
 
         </hibernate-configuration></strong></span>

 

2. Demo.java 

       

  

<span style="font-size:12px;">/**
          *
          */
         package cn.edu.bucea.domain;
 
         import java.io.Serializable;
 
         /**
          * @author JJG
          *
          */
         public class Demo implementsSerializable {
 
                   private static final longserialVersionUID = -2072913502409092000L;
                  
                   private String id;
                   private String name;
                   private String password;
                  
                   public Demo() {}
 
                   /**
                    * @param id
                    * @param name
                    * @param password
                    */
                   public Demo(String id, Stringname, String password) {
                            super();
                            this.id = id;
                            this.name = name;
                            this.password =password;
                   }
 
                   public String getId() {
                            return id;
                   }
 
                   public void setId(String id){
                            this.id = id;
                   }
 
                   public String getName() {
                            return name;
                   }
 
                   public void setName(Stringname) {
                            this.name = name;
                   }
 
                   public String getPassword() {
                            return password;
                   }
 
                   public voidsetPassword(String password) {
                            this.password =password;
                   }
 
                   @Override
                   public String toString() {
                            return "Demo[id=" + id + ", name=" + name + ", password=" +password
                                               +"]";
                   }
                  
         }</span>

 

Demo.hbm.xml

         

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/HibernateMapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
       
<hibernate-mapping>
 
    <class name="cn.edu.bucea.domain.Demo"table="DEMO">
        <id name="id" type="int">
            <column name="ID"/>
            <generator class="identity"/>
        </id>
        <property name="name" type="string">
            <column name="NAME"/>
        </property>
        <property name="password" type="string">
            <column name="PASSWORD"></column>
        </property>
    </class>
 
</hibernate-mapping>

把新的映射加入到Hibernate的配置中;

         例:<mapping resource=" cn/edu/bucea/domain/Demo.hbm.xml"/>

 

3.SessionfactoryUtil.java

importorg.hibernate.HibernateException;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.Configuration;
 
public classSessionFactoryUtil {
    private static SessionFactory sessionFactory;
    private static String CONFIG_FILE_LOCATION = "/cn/edu/bucea/config/hibernate.cfg.xml";
   
    static{
       try{
           sessionFactory = new Configuration().configure(CONFIG_FILE_LOCATION).
                  buildSessionFactory();
       }catch(HibernateExceptione){
           System.err.println("%%%% Error Creating SessionFactory %%%%");
           e.printStackTrace();
       }
    }
   
    public static SessionFactorygetSessionFactory() {
       return sessionFactory;
    }
   
    public static void main(String[]args) {
       System.out.println(getSessionFactory());
    }
 
}


 

DemoException.java

 

/**
 * @author JJG
 *  用户自定义异常类
 */
public class DemoException extends Exception {
 
    private static final long serialVersionUID = 704805066683813880L;
 
    publicDemoException(Exception e){
       super(e);
    }
   
    publicDemoException(String msg){
       super(msg);
    }
}

 

4. DemoDAO.java

 

importorg.hibernate.HibernateException;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
import cn.edu.bucea.domain.Demo;
importcn.edu.bucea.exception.DemoException;
importcn.edu.bucea.util.SessionFactoryUtil;
 
public class DemoDAO {
 
  public DemoDAO() {
  }
 
  public void saveDemo(Demodemo) throws DemoException{
     Session session= null;
     Transactiontransaction = null;//注意Session和Transaction的包
     try{
         session =SessionFactoryUtil.getSessionFactory().openSession();
         transaction= session.beginTransaction();
         session.save(demo);
         transaction.commit();
     } catch(HibernateExceptione){
         transaction.rollback();
         throw newDemoException(e.getMessage());
     } finally{
         if (session != null){
            session.close();
         }
     }
     //...
  }
}


 

5.DeomTest.java

 

import cn.edu.bucea.DAO.DemoDAO;
import cn.edu.bucea.domain.Demo;
import cn.edu.bucea.exception.DemoException;
 
/**
 * @author JJG
 * DemoDAO测试类
 */
public class DemoTest {
 
    public static void testSaveDemo() throws DemoException{
       Demo demo = new Demo();
       demo.setId(1);
       demo.setName("JJG");
       demo.setPassword("123");
      
       DemoDAO demoDAO = new DemoDAO();
       demoDAO.saveDemo(demo);
      
    }
    //…
 
    public static void main(String[] args) throws DemoException {
       testSaveDemo();
    //…
    }
   
}


 

 

6…

 

注:以上Hibernate框架的单独应用

===========================================================================

下一篇:SSH框架搭建过程---之Spring框架的使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值