跨向Hibernate(一)

从读Hibernate的手册开始了学习Hibernate的历程。
《与猫同乐》----乐的有些尴尬,因为在99%时,测试用了普通Java类,长时间滞留不前,把我的猫忘在门外了
 
1、配置数据源。
在Tomcat5中,修改conf\tomcat-users.xml文件,加入<user roles="admin" password="admin" username="admin">。启动Tomcat,进入管理页面,添加数据源,最终有如下信息加入项目的配置文件中:</user>
  <resource type="javax.sql.DataSource" name="jdbc/quickstart">
  <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></resource>
 
2、添加Hibernate库
把所需的库加入类路径中,或是项目Lib中
 
3、编写hibernate.cfg.xml文件,置于项目编译后的根目录下(在Eclipse或其他IDE中,放在源文件根目录下即可),内容类似下示:


    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    " http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
 
<hibernate-configuration></hibernate-configuration>
 
    <session-factory></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 resource="Cat.hbm.xml"></mapping>
 
   
 
 
 
 
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;
    }
 
}
 


    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
 
<hibernate-mapping></hibernate-mapping>
 
    <class table="CAT" name="net.sf.hibernate.examples.quickstart.Cat"></class>
 
       
        <id unsaved-value="null" type="string" name="id">
            <column not-null="true" sql-type="char(32)" name="CAT_ID">
            <generator class="uuid.hex">
        </generator></column></id>
 
       
        <property name="name">
            <column not-null="true" length="16" name="NAME">
        </column></property>
 
        <property name="sex"></property>
 
        <property name="weight"></property>
 
   
 


*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"%>
 
 
<%
          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){
            }
           
%>
 
 


 

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值