Hibernate初體驗Cat之快速上手
?
Hibernate的手冊里的Cat例子感覺很不明了,很難照著它輕松的運行起第一個例子,費了點周折,總算看到一點結(jié)果,如果你是新手,可以參考一下,少走一些彎路。
1.下載tomcat和Hibernate
Tomcat 5.0.27 | Tomcat 5.0.28 | Hibernate2.1.6
2. 安裝
以tomcat+mysql+hibernate為例
tomcat的安裝,及mysql的安裝和DBCP的配制參見
http://blog.csdn.net/ahxu/archive/2004/09/01/91611.aspx,這里就不提了,這里假設(shè)tomcat+mysql已經(jīng)配置并測試可用,這里%WebApp%代表你已配置好的一個web應(yīng)用的root,著重說一下hibernate的安裝,
1) 解壓下載的壓縮包,將解壓出來的hibernate2.jar復(fù)制到%WebApp%/WEB-INF/lib
2) 將解壓出來的lib目錄下的
cglib-full-2.0.2.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.4.jar
ehcache-0.9.jar
jta.jar
log4j-1.2.8.jar
odmg-3.0.jar
文件同樣復(fù)制到%WebApp%/WEB-INF/lib,具體請參見解壓出來的lib目錄下的readme.txt。
3) 將解壓出來的etc目錄下的
log4j.properties
文件復(fù)制到%WebApp%/WEB-INF/classes。
3.編寫相關(guān)文件
1) 按照參考文檔,配置hibernate,將以下代碼保存為hibernate.cfg.xml放在%WebApp%/WEB-INF/classes下
?
|
<property name="connection.datasource">java:comp/env/jdbc/mysql</property> <property name="show_sql">false</property> <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<!-- Mapping files --> <mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
|
NOTE:這里與hibernate文檔里的不一樣,這里指定數(shù)據(jù)源為mysql數(shù)據(jù)庫jdbc/mysql,方言dialect為net.sf.hibernate.dialect.MySQLDialect。
2) 將以下代碼保存為Cat.java,并生成相應(yīng)的Cat.class,放入%WebApp%/WEB-INF/classes,這里無論你用什么方法生成Cat.class,但最終Cat.class應(yīng)在%WebApp%/WEB-INF/classes/net/sf/hibernate/examples/quickstart目錄下
|
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; }
}
|
?
3) 將以下代碼保存為O/R映射文件Cat.hbm.xml,放入%WebApp%/WEB-INF/classes
|
<?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 |
4) 在數(shù)據(jù)庫內(nèi)建表,結(jié)構(gòu)如下
Column |???????? Type????????? | Modifiers
--------+-----------------------+-----------
cat_id | character(32)???????? | not null
name?? | character varying(16) | not null
sex??? | character(1)????????? |
weight | real????????????????? |
Indexes: cat_pkey primary key btree (cat_id)
5) 將以下代碼保存為HibernateUtil.java,并生成相應(yīng)的HibernateUtil.class,放入%WebApp%/WEB-INF/classes,同樣注意package
|
package net.sf.hibernate.examples.quickstart; import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory; import net.sf.hibernate.*; import net.sf.hibernate.cfg.*; 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(); } }
|
?
NOTE:這里與hibernate文檔也不同,原文檔編繹時缺少2個包,這里已加上。
6) 將以下代碼保存為test.jsp,放入%WebApp%/,用http測試
|
<%@ page language="java" pageEncoding="GB2312" %><%@ page import="net.sf.hibernate.Transaction"%><%@ page import="net.sf.hibernate.Session"%><%@ page import="net.sf.hibernate.cfg.*"%><%@ page import="net.sf.hibernate.Query"%><%@ page import="net.sf.hibernate.examples.quickstart.HibernateUtil"%><%@ page import="net.sf.hibernate.examples.quickstart.Cat"%><%@ page import="java.util.*"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"><html><head><title>Lomboz JSP</title></head><body bgcolor="#FFFFFF"> <% //添加一只Cat
Session ses = HibernateUtil.currentSession(); Transaction tx= ses.beginTransaction();
Cat princess = new Cat(); princess.setName("ahxu"); princess.setSex('F'); princess.setWeight(7.4f);
ses.save(princess); tx.commit();
HibernateUtil.closeSession();
//讀取庫里所有Cat
ses = HibernateUtil.currentSession(); tx= ses.beginTransaction();
Query query = ses.createQuery("select c from Cat as c where c.sex = :sex"); query.setCharacter("sex", 'F'); for (Iterator it = query.iterate(); it.hasNext();) { Cat cat = (Cat) it.next(); out.println("Female Cat: " + cat.getName() ); }
tx.commit(); HibernateUtil.closeSession(); %> </body> </html>
|
?
小結(jié)
步驟基本與原文檔步驟相同,只是做了一些補充,方便上手,這里并沒有對其中的一些配置做具體解釋,如有疑問請參見發(fā)行包中的相關(guān)文檔。
以上tomcat5.027 + hibernate2.1.6測試通過