跨向Hibernate(一)

来源:互联网 发布:南康教育网络办公系统 编辑:程序博客网 时间:2024/06/18 10:09
从读Hibernate的手册开始了学习Hibernate的历程。
《与猫同乐》----乐的有些尴尬,因为在99%时,测试用了普通Java类,长时间滞留不前,把我的猫忘在门外了
 
1、配置数据源。
在Tomcat5中,修改conf/tomcat-users.xml文件,加入<user username="admin" password="admin" roles="admin"/>。启动Tomcat,进入管理页面,添加数据源,最终有如下信息加入项目的配置文件中:
  <Resource name="jdbc/quickstart" type="javax.sql.DataSource"/>
  <ResourceParams name="jdbc/quickstart">
    <parameter>
      <name>maxWait</name>
      <value>5000</value>
    </parameter>
    <parameter>
      <name>maxActive</name>
      <value>4</value>
    </parameter>
    <parameter>
      <name>password</name>
      <value>secret</value>
    </parameter>
    <parameter>
      <name>url</name>
      <value>jdbc:mysql://localhost/test</value>
    </parameter>
    <parameter>
      <name>driverClassName</name>
      <value>com.mysql.jdbc.Driver</value>
    </parameter>
    <parameter>
      <name>maxIdle</name>
      <value>2</value>
    </parameter>
    <parameter>
      <name>username</name>
      <value>quickstart</value>
    </parameter>
  </ResourceParams>
 
2、添加Hibernate库
把所需的库加入类路径中,或是项目Lib中
 
3、编写hibernate.cfg.xml文件,置于项目编译后的根目录下(在Eclipse或其他IDE中,放在源文件根目录下即可),内容类似下示:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
 
        <property name="connection.datasource">java:comp/env/jdbc/quickstart</property>
        <property name="show_sql">false</property>
        <property name="dialect">net.sf.hibernate.dialect.PostgreSQLDialect</property>
 
        <!-- Mapping files -->
        <mapping resource="Cat.hbm.xml"/>
 
    </session-factory>
 
 
</hibernate-configuration>
 
4、编写相应的映射类和配置文件,并放在同一目录下,例如:
 
package net.sf.hibernate.examples.quickstart;
 
public class Cat {
 
    private String id;
    private String name;
    private char sex;
    private float weight;
 
    public Cat() {
    }
 
    public String getId() {
        return id;
    }
 
    private void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public char getSex() {
        return sex;
    }
 
    public void setSex(char sex) {
        this.sex = sex;
    }
 
    public float getWeight() {
        return weight;
    }
 
    public void setWeight(float weight) {
        this.weight = weight;
    }
 
}
 
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
 
<hibernate-mapping>
 
    <class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">
 
        <!-- A 32 hex character is our surrogate key. It's automatically
            generated by Hibernate with the UUID pattern. -->
        <id name="id" type="string" unsaved-value="null" >
            <column name="CAT_ID" sql-type="char(32)" not-null="true"/>
            <generator class="uuid.hex"/>
        </id>
 
        <!-- A cat has to have a name, but it shouldn' be too long. -->
        <property name="name">
            <column name="NAME" length="16" not-null="true"/>
        </property>
 
        <property name="sex"/>
 
        <property name="weight"/>
 
    </class>
 
</hibernate-mapping>

*5、编写自定义SessionFactory类,例如:(此为Hibernate自带的示例)
 
HibernateUtil.java
 
package net.sf.hibernate.examples.quickstart;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
public class HibernateUtil {
 
    private static Log log = LogFactory.getLog(HibernateUtil.class);
 
    private static final SessionFactory sessionFactory;
 
    static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static final ThreadLocal session = new ThreadLocal();
 
    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }
 
    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }
 
}
6、编写测试Jsp或Serverlet,注意,这里是在Tomcat环境下,不能用普通Java类示例Jsp
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="net.sf.hibernate.Session"%>
<%@ page import="net.sf.hibernate.HibernateException"%>
<%@ page import="net.sf.hibernate.Transaction"%>
<%@ page import="net.sf.hibernate.examples.quickstart.Cat"%>
<%@ page import="net.sf.hibernate.examples.quickstart.HibernateUtil"%>
<html>
<body>
<hr>
<%
          try{
         Session ssession;
            ssession = HibernateUtil.currentSession();
            Transaction tx= ssession.beginTransaction();
            Cat princess = new Cat();
            princess.setName("Princess");
            princess.setSex('F');
            princess.setWeight(7.4f);
 
            ssession.save(princess);
            tx.commit();
 
            HibernateUtil.closeSession();
            }catch(HibernateException e){
            }
           
%>
<hr>
</body>
</html>
原创粉丝点击