读书人

Hibernate Reference官方文档实践日志

发布时间: 2012-07-01 13:15:00 作者: rapoo

Hibernate Reference官方文档实践日记一

?????? 参照着 Hibernate Reference Documentation 官方文档一步步操作的过程中,还是会产生这样或者那样的错误,从而不能完整运行程序,现在幸得weimingtom兄的一篇博文启发(可惜的是他已经删除了该博文可以访问的链接),现在我也一步步完成了 Hibernate Reference Documentation 官方文档第一章的部分内容,下面一一说明,以备他人借鉴,少走弯路。

?????最新版 Hibernate Reference 3.6.5文档中的中文翻译比3.3.2中的多一些,下面参照3.6.5版的中文文档操作。

?

1. 新建project文件夹“Hellohibernate”,在Hellohibernate文件夹下面创建下面几个目录几子目录 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.hibernate.tutorials</groupId> <artifactId>Hellohibernate</artifactId> <version>1.0.0-SNAPSHOT</version> <name>First Hibernate Tutorial</name> <build> <!-- we dont want the version to be part of the generated war file name --> <finalName>${artifactId}</finalName> </build> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.3.2.GA</version> </dependency> <!-- Because this is a web app, we also have a dependency on the servlet api. --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> </dependency> <!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.5.6</version> </dependency> <!-- Hibernate gives you a choice of bytecode providers between cglib and javassist --> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.10.0.GA</version> </dependency> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.1</version> </dependency> </dependencies></project>

?

3. 创建第一个class

创建目录package org.hibernate.tutorial.domain;import java.util.Date;public class Event { private Long id; private String title; private Date date; public Event() {} public Long getId() { return id; } private void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }}

?

4. 创建映射文件

同时在<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator type="timestamp" column="EVENT_DATE"/> <property name="title"/> </class></hibernate-mapping>

?

5.配置启动HSQLDB数据库

在项目Hellohibernate根目录下创建一个lib和一个data目录,下载hsqldb 1.X系列版本hsqldb_1_8_1_3.zip,解压缩出来的hsqldb.jar文件放到lib路径下。 此时在dos窗口命令行中,进入data目录,运行

java -classpath ../lib/hsqldb.jar org.hsqldb.Server

?

使其运行在“服务器模式”下。

?

6.配置Hibernate连接数据库

在项目根目录下,新建src/main/resources子目录,在该目录下新建文件hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <!-- Database connection settings -->        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>        <property name="connection.url">jdbc:hsqldb:hsql://localhost/data/test</property>        <property name="connection.username">SA</property>        <property name="connection.password"></property>        <!-- JDBC connection pool (use the built-in) -->        <property name="connection.pool_size">1</property>        <!-- SQL dialect -->        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>        <!-- Enable Hibernate's automatic session context management -->        <property name="current_session_context_class">thread</property>        <!-- Disable the second-level cache  -->        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        <!-- Echo all executed SQL to stdout -->        <property name="show_sql">true</property>        <!-- Drop and re-create the database schema on startup -->        <property name="hbm2ddl.auto">update</property>        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>    </session-factory></hibernate-configuration>

?

7.? 用Maven构建 安装Maven后,在项目根路径下(该路径下包含pom.xml文件)执行命令

 mvn compile

?看到信息

…… BUILD SUCCESSFUL……

?

表示编译成功。

?

8.启动和辅助类:

在项目根目录下新建路径package org.hibernate.tutorial.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; }}

?

9.配置日志文件

?

配置一个日志(logging)系统 — Hibernate 使用通用日志接口,允许你在 Log4j 和 JDK 1.4 日志之间进行选择。多数开发者更喜欢 Log4j:从 Hibernate 的发布包中(它在 package org.hibernate.tutorial;import org.hibernate.Session;import java.util.*;import org.hibernate.tutorial.domain.Event;import org.hibernate.tutorial.util.HibernateUtil;public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager(); if (args[0].equals("store")) { mgr.createAndStoreEvent("My Event", new Date()); } HibernateUtil.getSessionFactory().close(); }private void createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); }}

?

11.执行测试

在项目根路径下执行

mvn compile

?编译所有的类文件

?

然后执行如下的命令(再确保hsqldb已经启动的情况下):

mvn exec:java -Dexec.main-Dexec.args="store"

?

会看到,编译以后,Hibernate 根据你的配置启动,并产生一大堆的输出日志。在日志最后你会看到下面这行:

Dexec.main-Dexec.args="list"

?在输出日志中将看到类似下面的输出:

Event: MY Event Time: 2011-07-04 10:09:13.255Event: MY Event Time: 2011-07-04 10:52:55.532………………[INFO]  --------------------------------------------------------------------[INFO]  BUILD SUCCESS[INFO]  --------------------------------------------------------------------………………[INFO]  --------------------------------------------------------------------

?经过上面步骤,第一个hibernate示例运行成功了。具体里面的一些代码,命令等含义,请参照原官方文档以及相应的文档。本文只是配置跑通了该示例程序,没有进行详细解释。

?

附可运行代码下载: