Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2566314
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-08-01 20:04:11

第 1 章 教程

1.1. 第一部分 - 第一个 Hibernate 应用程序

    1.1.1. 设置
    1.1.2. 第一个 class
    1.1.3. 映射文件
    1.1.4. Hibernate 配置
    1.1.5. 用 Maven 构建
    1.1.6. 启动和辅助类
    1.1.7. 加载并存储对象

1.2. 第二部分 - 关联映射

    1.2.1. 映射 Person 类
    1.2.2. 单向 Set-based 的关联
    1.2.3. 使关联工作
    1.2.4. 值类型的集合
    1.2.5. 双向关联
    1.2.6. 使双向连起来

1.3. 第三部分 - EventManager web 应用程序

    1.3.1. 编写基本的 servlet
    1.3.2. 处理与渲染
    1.3.3. 部署与测试

1.4. 总结

面向新用户,从一个简单的使用内存数据库的例子开始,本章提供对 Hibernate 的逐步介绍。本教程基于 Michael Gloegl 早期编写的手册。所有代码都包含在 tutorials/web 目录下。

重要

本教程期望用户具备 Java 和 SQL 知识。如果你这方面的知识有限,我们建议你在学习 Hibernate 之前先好好了解这些技术。

注意

本版本在源代码目录 tutorial/eg 下还包含另外一个例程。

(一个用 Java 编写的内存数据库)来避免花费篇章对数据库服务器的安装/配置进行解释。

所鼓吹的“标准格式”。特别是 Maven,它的资源对这个有着很好的描述。因为本教程使用的是 web 应用程序,我么将创建和使用 src/main/java、src/main/resources 和 src/main/webapp 目录。

在本教程里我们将使用 Maven,利用其 transitive dependency 管理以及根据 Maven 描述符用 IDE 自动设置项目的能力。

  1. <project xmlns=""
  2.          xmlns:xsi=""
  3.          xsi:schemaLocation=" ">

  4.     <modelVersion
  5. >4.0.0</modelVersion>

  6.     <groupId
  7. >org.hibernate.tutorials</groupId>
  8.     <artifactId
  9. >hibernate-tutorial</artifactId>
  10.     <version
  11. >1.0.0-SNAPSHOT</version>
  12.     <name
  13. >First Hibernate Tutorial</name>

  14.     <build>
  15.          <!-- we dont want the version to be part of the generated war file name -->
  16.          <finalName
  17. >${artifactId}</finalName>
  18.     </build>

  19.     <dependencies>
  20.         <dependency>
  21.             <groupId
  22. >org.hibernate</groupId>
  23.             <artifactId
  24. >hibernate-core</artifactId>
  25.         </dependency>

  26.         <!-- Because this is a web app, we also have a dependency on the servlet api. -->
  27.         <dependency>
  28.             <groupId
  29. >javax.servlet</groupId>
  30.             <artifactId
  31. >servlet-api</artifactId>
  32.         </dependency>

  33.         <!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend -->
  34.         <dependency>
  35.             <groupId
  36. >org.slf4j</groupId>
  37.             <artifactId
  38. >slf4j-simple</artifactId>
  39.         </dependency>

  40.         <!-- Hibernate gives you a choice of bytecode providers between cglib and javassist -->
  41.         <dependency>
  42.             <groupId
  43. >javassist</groupId>
  44.             <artifactId
  45. >javassist</artifactId>
  46.         </dependency>
  47.     </dependencies>

  48. </project>
提示

It is not a requirement to use Maven. If you wish to use something else to build this tutorial (such as Ant), the layout will remain the same. The only change is that you will need to manually account for all the needed dependencies. If you use something like providing transitive dependency management you would still use the dependencies mentioned below. Otherwise, you'd need to grab all dependencies, both explicit and transitive, and add them to the project's classpath. If working from the Hibernate distribution bundle, this would mean hibernate3.jar, all artifacts in the lib/required directory and all files from either the lib/bytecode/cglib or lib/bytecode/javassist directory; additionally you will need both the servlet-api jar and one of the slf4j logging backends.

把这个文件保存为项目根目录下的 pom.xml。

  1. package org.hibernate.tutorial.domain;

  2. import java.util.Date;

  3. public class Event {
  4.     private Long id;

  5.     private String title;
  6.     private Date date;

  7.     public Event() {}

  8.     public Long getId() {
  9.         return id;
  10.     }

  11.     private void setId(Long id) {
  12.         this.id = id;
  13.     }

  14.     public Date getDate() {
  15.         return date;
  16.     }

  17.     public void setDate(Date date) {
  18.         this.date = date;
  19.     }

  20.     public String getTitle() {
  21.         return title;
  22.     }

  23.     public void setTitle(String title) {
  24.         this.title = title;
  25.     }
  26. }

  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4.         "">

  5. <hibernate-mapping package="org.hibernate.tutorial.domain">
  6. [...]
  7. </hibernate-mapping>

  1. <hibernate-mapping package="org.hibernate.tutorial.domain">

  2.     <class name="Event" table="EVENTS">

  3.     </class>

  4. </hibernate-mapping>

  1. <hibernate-mapping package="org.hibernate.tutorial.domain">

  2.     <class name="Event" table="EVENTS">
  3.         <id name="id" column="EVENT_ID">
  4.             <generator class="native"/>
  5.         </id>
  6.     </class>

  7. </hibernate-mapping>

最后我们在映射文件里面包含需要持久化属性的声明。默认情况下,类里面的属性都被视为非持久化的:

 
  1. <hibernate-mapping package="org.hibernate.tutorial.domain">

  2.     <class name="Event" table="EVENTS">
  3.         <id name="id" column="EVENT_ID">
  4.             <generator class="native"/>
  5.         </id>
  6.         <property name="date" type="timestamp" column="EVENT_DATE"/>
  7.         <property name="title"/>
  8.     </class>

  9. </hibernate-mapping>

和 id 元素一样,property 元素的 name 属性告诉 Hibernate 使用哪个 getter 和 setter 方法。在此例中,Hibernate 会寻找 getDate()、setDate()、getTitle() 和 setTitle() 方法。

注意

为什么 date 属性的映射含有 column attribute,而 title 却没有?当没有设定 column attribute 的时候,Hibernate 缺省地使用 JavaBean 的属性名作为字段名。对于 title,这样工作得很好。然而,date 在多数的数据库里,是一个保留关键字,所以我们最好把它映射成一个不同的名字。

另一有趣的事情是 title 属性缺少一个 type attribute。我们在映射文件里声明并使用的类型,却不是我们期望的那样,是 Java 数据类型,同时也不是 SQL 数据库的数据类型。这些类型就是所谓的 Hibernate 映射类型(mapping types),它们能把 Java 数据类型转换到 SQL 数据类型,反之亦然。再次重申,如果在映射文件中没有设置 type 属性的话,Hibernate 会自己试着去确定正确的转换类型和它的映射类型。在某些情况下这个自动检测机制(在 Java 类上使用反射机制)不会产生你所期待或需要的缺省值。date 属性就是个很好的例子,Hibernate 无法知道这个属性(java.util.Date 类型的)应该被映射成:SQL date,或 timestamp,还是 time 字段。在此例中,把这个属性映射成 timestamp 转换器,这样我们预留了日期和时间的全部信息。

提示

当处理映射文件时,Hibernate 用反射(reflection)来决定这个映射类型。这需要时间和资源,所以如果你注重启动性能,你应该考虑显性地定义所用的类型。

把这个映射文件保存为 src/main/resources/org/hibernate/tutorial/domain/Event.hbm.xml。

和 。然而,在本教程里我们将使用 Hibernate 内置的连接池。

小心

嵌入的 Hibernate 连接池不用于产品环境。它缺乏连接池里的几个功能。

为了保存 Hibernate 的配置,我们可以使用一个简单的 hibernate.properties 文件,或者一个稍微复杂的 hibernate.cfg.xml,甚至可以完全使用程序来配置 Hibernate。多数用户更喜欢使用 XML 配置文件:

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.         "">

  5. <hibernate-configuration>

  6.     <session-factory>

  7.         <!-- Database connection settings -->
  8.         <property name="connection.driver_class"
  9. >org.hsqldb.jdbcDriver</property>
  10.         <property name="connection.url"
  11. >jdbc:hsqldb:hsql://localhost</property>
  12.         <property name="connection.username"
  13. >sa</property>
  14.         <property name="connection.password"
  15. ></property>

  16.         <!-- JDBC connection pool (use the built-in) -->
  17.         <property name="connection.pool_size"
  18. >1</property>

  19.         <!-- SQL dialect -->
  20.         <property name="dialect"
  21. >org.hibernate.dialect.HSQLDialect</property>

  22.         <!-- Enable Hibernate
注意

请注意,这个配置文件指定了一个不同的 DTD。

注意这个 XML 配置使用了一个不同的 DTD。在这里,我们配置了 Hibernate 的SessionFactory — 一个关联于特定数据库全局的工厂(factory)。如果你要使用多个数据库,就要用多个的 ,通常把它们放在多个配置文件中(为了更容易启动)。

签名 4 个 property 元素包含了 JDBC 连接所必需的配置。方言 property 元素指定了 Hibernate 生成的特定 SQL 语句。

提示

In most cases, Hibernate is able to properly determine which dialect to use. See for more information.

最开始的 4 个 property 元素包含必要的 JDBC 连接信息。方言(dialect)的 property 元素指明 Hibernate 生成的特定 SQL 变量。你很快会看到,Hibernate 对持久化上下文的自动 session 管理就会派上用场。 打开 hbm2ddl.auto 选项将自动生成数据库模式(schema)- 直接加入数据库中。当然这个选项也可以被关闭(通过去除这个配置选项)或者通过 Ant 任务 SchemaExport 的帮助来把数据库 schema 重定向到文件中。最后,在配置中为持久化类加入映射文件。

把这个文件保存为 src/main/resources 目录下的 hibernate.cfg.xml。

获得 Maven。Maen 将读取我们先前创建的 /pom.xml 并知道执行基本的项目任务。首先,让我们运行 compile 目标来确保我们可以编译到目前为止的所有程序:

  1. [hibernateTutorial]$ mvn compile
  2. [INFO] Scanning for projects...
  3. [INFO] ------------------------------------------------------------------------
  4. [INFO] Building First Hibernate Tutorial
  5. [INFO] task-segment: [compile]
  6. [INFO] ------------------------------------------------------------------------
  7. [INFO] [resources:resources]
  8. [INFO] Using default encoding to copy filtered resources.
  9. [INFO] [compiler:compile]
  10. [INFO] Compiling 1 source file to /home/steve/projects/sandbox/hibernateTutorial/target/classes
  11. [INFO] ------------------------------------------------------------------------
  12. [INFO] BUILD SUCCESSFUL
  13. [INFO] ------------------------------------------------------------------------
  14. [INFO] Total time: 2 seconds
  15. [INFO] Finished at: Tue Jun 09 12:25:25 CDT 2009
  16. [INFO] Final Memory: 5M/547M
  17. [INFO] ------------------------------------------------------------------------

  1. package org.hibernate.tutorial.util;

  2. import org.hibernate.SessionFactory;
  3. import org.hibernate.cfg.Configuration;

  4. public class HibernateUtil {

  5.     private static final SessionFactory sessionFactory = buildSessionFactory();

  6.     private static SessionFactory buildSessionFactory() {
  7.         try {
  8.             // Create the SessionFactory from hibernate.cfg.xml
  9.             return new Configuration().configure().buildSessionFactory();
  10.         }
  11.         catch (Throwable ex) {
  12.             // Make sure you log the exception, as it might be swallowed
  13.             System.err.println("Initial SessionFactory creation failed." + ex);
  14.             throw new ExceptionInInitializerError(ex);
  15.         }
  16.     }

  17.     public static SessionFactory getSessionFactory() {
  18.         return sessionFactory;
  19.     }

  20. }

  1. package org.hibernate.tutorial;

  2. import org.hibernate.Session;

  3. import java.util.*;

  4. import org.hibernate.tutorial.domain.Event;
  5. import org.hibernate.tutorial.util.HibernateUtil;

  6. public class EventManager {

  7.     public static void main(String[] args) {
  8.         EventManager mgr = new EventManager();

  9.         if (args[0].equals("store")) {
  10.             mgr.createAndStoreEvent("My Event", new Date());
  11.         }

  12.         HibernateUtil.getSessionFactory().close();
  13.     }

  14.     private void createAndStoreEvent(String title, Date theDate) {
  15.         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  16.         session.beginTransaction();

  17.         Event theEvent = new Event();
  18.         theEvent.setTitle(title);
  19.         theEvent.setDate(theDate);
  20.         session.save(theEvent);

  21.         session.getTransaction().commit();
  22.     }

  23. }

A org.hibernate.Session is designed to represent a single unit of work (a single atomic piece of work to be performed). For now we will keep things simple and assume a one-to-one granularity between a Hibernate org.hibernate.Session and a database transaction. To shield our code from the actual underlying transaction system we use the Hibernate org.hibernate.Transaction API. In this particular case we are using JDBC-based transactional semantics, but it could also run with JTA.

for more information about transaction handling and demarcation. The previous example also skipped any error handling and rollback.

要运行它,我们将使用 Maven exec 插件以及必要的 classpath 设置来进行调用:mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="store"。

注意

你可能需要先执行 mvn compile。

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

[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?, ?, ?)

执行 HQL INSERT 语句的例子如下:

我们想要列出所有已经被存储的 events,就要增加一个条件分支选项到 main 方法中:

  
  1. if (args[0].equals("store")) {
  2.             mgr.createAndStoreEvent("My Event", new Date());
  3.         }
  4.         else if (args[0].equals("list")) {
  5.             List events = mgr.listEvents();
  6.             for (int i = 0; i < events.size(); i++) {
  7.                 Event theEvent = (Event) events.get(i);
  8.                 System.out.println(
  9.                         "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()
  10.                 );
  11.             }
  12.         }

我们也增加一个新的 listEvents() 方法:

   
  1. private List listEvents() {
  2.         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  3.         session.beginTransaction();
  4.         List result = session.createQuery("from Event").list();
  5.         session.getTransaction().commit();
  6.         return result;
  7.     }

Here, we are using a Hibernate Query Language (HQL) query to load all existing Event objects from the database. Hibernate will generate the appropriate SQL, send it to the database and populate Event objects with the data. You can create more complex queries with HQL. See for more information.

现在我们可以再次用 Maven exec plugin - mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="list" 调用新的功能了。

  1. package org.hibernate.tutorial.domain;

  2. public class Person {

  3.     private Long id;
  4.     private int age;
  5.     private String firstname;
  6.     private String lastname;

  7.     public Person() {}

  8.     // Accessor methods for all properties, private setter for 'id'

  9. }

  1. <hibernate-mapping package="org.hibernate.tutorial.domain">

  2.     <class name="Person" table="PERSON">
  3.         <id name="id" column="PERSON_ID">
  4.             <generator class="native"/>
  5.         </id>
  6.         <property name="age"/>
  7.         <property name="firstname"/>
  8.         <property name="lastname"/>
  9.     </class>

  10. </hibernate-mapping>

  1. public class Person {

  2.     private Set events = new HashSet();

  3.     public Set getEvents() {
  4.         return events;
  5.     }

  6.     public void setEvents(Set events) {
  7.         this.events = events;
  8.     }
  9. }

  1. <class name="Person" table="PERSON">
  2.     <id name="id" column="PERSON_ID">
  3.         <generator class="native"/>
  4.     </id>
  5.     <property name="age"/>
  6.     <property name="firstname"/>
  7.     <property name="lastname"/>

  8.     <set name="events" table="PERSON_EVENT">
  9.         <key column="PERSON_ID"/>
  10.         <many-to-many column="EVENT_ID" class="Event"/>
  11.     </set>

  12. </class>

  1. _____________ __________________
  2. | | | | _____________
  3. | EVENTS | | PERSON_EVENT | | |
  4. |_____________| |__________________| | PERSON |
  5. | | | | |_____________|
  6. | *EVENT_ID | <--> | *EVENT_ID | | |
  7. | EVENT_DATE | | *PERSON_ID | <--> | *PERSON_ID |
  8. | TITLE | |__________________| | AGE |
  9. |_____________| | FIRSTNAME |
  10. | LASTNAME |
  11. |_____________|

  1. private void addPersonToEvent(Long personId, Long eventId) {
  2.         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  3.         session.beginTransaction();

  4.         Person aPerson = (Person) session.load(Person.class, personId);
  5.         Event anEvent = (Event) session.load(Event.class, eventId);
  6.         aPerson.getEvents().add(anEvent);

  7.         session.getTransaction().commit();
  8.     }

  1. private void addPersonToEvent(Long personId, Long eventId) {
  2.         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  3.         session.beginTransaction();

  4.         Person aPerson = (Person) session
  5.                 .createQuery("select p from Person p left join fetch p.events where p.id = :pid")
  6.                 .setParameter("pid", personId)
  7.                 .uniqueResult(); // Eager fetch the collection so we can use it detached
  8.         Event anEvent = (Event) session.load(Event.class, eventId);

  9.         session.getTransaction().commit();

  10.         // End of first unit of work

  11.         aPerson.getEvents().add(anEvent); // aPerson (and its collection) is detached

  12.         // Begin second unit of work

  13.         Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
  14.         session2.beginTransaction();
  15.         session2.update(aPerson); // Reattachment of aPerson

  16.         session2.getTransaction().commit();
  17.     }

  1. else if (args[0].equals("addpersontoevent")) {
  2.             Long eventId = mgr.createAndStoreEvent("My Event", new Date());
  3.             Long personId = mgr.createAndStorePerson("Foo", "Bar");
  4.             mgr.addPersonToEvent(personId, eventId);
  5.             System.out.println("Added person " + personId + " to event " + eventId);
  6.         }

  1. private Set emailAddresses = new HashSet();

  2.     public Set getEmailAddresses() {
  3.         return emailAddresses;
  4.     }

  5.     public void setEmailAddresses(Set emailAddresses) {
  6.         this.emailAddresses = emailAddresses;
  7.     }

  1. <set name="emailAddresses" table="PERSON_EMAIL_ADDR">
  2.             <key column="PERSON_ID"/>
  3.             <element type="string" column="EMAIL_ADDR"/>
  4.         </set>

  1. _____________ __________________
  2. | | | | _____________
  3. | EVENTS | | PERSON_EVENT | | | ___________________
  4. |_____________| |__________________| | PERSON | | |
  5. | | | | |_____________| | PERSON_EMAIL_ADDR |
  6. | *EVENT_ID | <--> | *EVENT_ID | | | |___________________|
  7. | EVENT_DATE | | *PERSON_ID | <--> | *PERSON_ID | <--> | *PERSON_ID |
  8. | TITLE | |__________________| | AGE | | *EMAIL_ADDR |
  9. |_____________| | FIRSTNAME | |___________________|
  10. | LASTNAME |
  11. |_____________|

  1. private void addEmailToPerson(Long personId, String emailAddress) {
  2.         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  3.         session.beginTransaction();

  4.         Person aPerson = (Person) session.load(Person.class, personId);
  5.         // adding to the emailAddress collection might trigger a lazy load of the collection
  6.         aPerson.getEmailAddresses().add(emailAddress);

  7.         session.getTransaction().commit();
  8.     }

  1. private Set participants = new HashSet();

  2.     public Set getParticipants() {
  3.         return participants;
  4.     }

  5.     public void setParticipants(Set participants) {
  6.         this.participants = participants;
  7.     }

  1. <set name="participants" table="PERSON_EVENT" inverse="true">
  2.             <key column="EVENT_ID"/>
  3.             <many-to-many column="PERSON_ID" class="Person"/>
  4.         </set>

  1. protected Set getEvents() {
  2.         return events;
  3.     }

  4.     protected void setEvents(Set events) {
  5.         this.events = events;
  6.     }

  7.     public void addToEvent(Event event) {
  8.         this.getEvents().add(event);
  9.         event.getParticipants().add(this);
  10.     }

  11.     public void removeFromEvent(Event event) {
  12.         this.getEvents().remove(event);
  13.         event.getParticipants().remove(this);
  14.     }

  1. package org.hibernate.tutorial.web;

  2. // Imports

  3. public class EventManagerServlet extends HttpServlet {

  4.     protected void doGet(
  5.             HttpServletRequest request,
  6.             HttpServletResponse response) throws ServletException, IOException {

  7.         SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" );

  8.         try {
  9.             // Begin unit of work
  10.             HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

  11.             // Process request and render page...

  12.             // End unit of work
  13.             HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
  14.         }
  15.         catch (Exception ex) {
  16.             HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
  17.             if ( ServletException.class.isInstance( ex ) ) {
  18.                 throw ( ServletException ) ex;
  19.             }
  20.             else {
  21.                 throw new ServletException( ex );
  22.             }
  23.         }
  24.     }

  25. }

  1. // Write HTML header
  2.         PrintWriter out = response.getWriter();
  3.         out.println("Event Manager");

  4.         // Handle actions
  5.         if ( "store".equals(request.getParameter("action")) ) {

  6.             String eventTitle = request.getParameter("eventTitle");
  7.             String eventDate = request.getParameter("eventDate");

  8.             if ( "".equals(eventTitle) || "".equals(eventDate) ) {
  9.                 out.println("Please enter event title and date.");
  10.             }
  11.             else {
  12.                 createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));
  13.                 out.println("Added event.");
  14.             }
  15.         }

  16.         // Print page
  17.        printEventForm(out);
  18.        listEvents(out, dateFormatter);

  19.        // Write HTML footer
  20.        out.println(" ");
  21.        out.flush();
  22.        out.close();

  1. private void printEventForm(PrintWriter out) {
  2.         out.println("Add new event:");
  3.         out.println("
    ");
  4.         out.println("Title:
    "
    );
  5.         out.println("Date (e.g. 24.12.2009):
    "
    );
  6.         out.println("");
  7.         out.println("");
  8.     }

  1. private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) {

  2.         List result = HibernateUtil.getSessionFactory()
  3.                 .getCurrentSession().createCriteria(Event.class).list();
  4.         if (result.size() > 0) {
  5.             out.println("Events in database:");
  6.             out.println("");
  7.             out.println("
  8. ");
  9.             out.println("
  10. ");
  11.             out.println("
  12. ");
  13.             out.println("
  14. ");
  15.             Iterator it = result.iterator();
  16.             while (it.hasNext()) {
  17.                 Event event = (Event) it.next();
  18.                 out.println("
  19. ");
  20.                 out.println("
  21. ");
  22.                 out.println("
  23. ");
  24.                 out.println("
  25. ");
  26.             }
  27.             out.println("
  28. Event titleEvent date
    " + event.getTitle() + "" + dateFormatter.format(event.getDate()) + "
    "
    );
  29.         }
  30.     }

  1. protected void createAndStoreEvent(String title, Date theDate) {
  2.         Event theEvent = new Event();
  3.         theEvent.setTitle(title);
  4.         theEvent.setDate(theDate);

  5.         HibernateUtil.getSessionFactory()
  6.                 .getCurrentSession().save(theEvent);
  7.     }

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.4"
  3.     xmlns=""
  4.     xmlns:xsi=""
  5.     xsi:schemaLocation=" /web-app_2_4.xsd">

  6.     <servlet>
  7.         <servlet-name>Event Manager</servlet-name>
  8.         <servlet-class>org.hibernate.tutorial.web.EventManagerServlet</servlet-class>
  9.     </servlet>

  10.     <servlet-mapping>
  11.         <servlet-name>Event Manager</servlet-name>
  12.         <url-pattern>/eventmanager</url-pattern>
  13.     </servlet-mapping>
  14. </web-app>

and follow the installation instructions. Our application requires no changes to the standard Tomcat configuration.

在部署完,启动 Tomcat 之后,通过 进行访问你的应用,在第一次 servlet 请求发生时,请在 Tomcat log 中确认你看到 Hibernate 被初始化了(HibernateUtil 的静态初始化器被调用),假若有任何异常抛出,也可以看到详细的输出。

上找到。

阅读(1832) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~