alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  
\");\n" " out.println(\"<td>\" + dateFormatter.format(event.getDate()) " "+ \"</td>\");\n" " out.println(\"</tr>\");\n" " }\n" " out.println(\"</table>\");\n" " }\n" " }]]>" msgstr "" "private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) {\n" "\n" " List result = HibernateUtil.getSessionFactory()\n" " .getCurrentSession().createCriteria(Event.class).list" "();\n" " if (result.size() > 0) {\n" " out.println(\"<h2>Events in database:</h2>\");\n" " out.println(\"<table border='1'>\");\n" " out.println(\"<tr>\");\n" " out.println(\"<th>Event title</th>\");\n" " out.println(\"<th>Event date</th>\");\n" " out.println(\"</tr>\");\n" " for (Iterator it = result.iterator(); it.hasNext();) {\n" " Event event = (Event) it.next();\n" " out.println(\"<tr>\");\n" " out.println(\"<td>\" + event.getTitle() + \"</td>" "\");\n" " out.println(\"<td>\" + dateFormatter.format(event.getDate" "()) + \"</td>\");\n" " out.println(\"</tr>\");\n" " }\n" " out.println(\"</table>\");\n" " }\n" "}" #. Tag: para #: tutorial.xml:1052 #, no-c-format msgid "" "Finally, the <literal>store action is dispatched to the " "<literal>createAndStoreEvent() method, which also uses the " "<literal>Session of the current thread:" msgstr "" "最后,<literal>store 动作会被导向到 createAndStoreEvent()" "</literal> 方法,它也使用当前线程的 Session:" #. Tag: programlisting #: tutorial.xml:1058 #, fuzzy, no-c-format msgid "" "<![CDATA[ protected void createAndStoreEvent(String title, Date theDate) " "{\n" " Event theEvent = new Event();\n" " theEvent.setTitle(title);\n" " theEvent.setDate(theDate);\n" "\n" " HibernateUtil.getSessionFactory()\n" " .getCurrentSession().save(theEvent);\n" " }]]>" msgstr "" "protected void createAndStoreEvent(String title, Date theDate) {\n" " Event theEvent = new Event();\n" " theEvent.setTitle(title);\n" " theEvent.setDate(theDate);\n" "\n" " HibernateUtil.getSessionFactory()\n" " .getCurrentSession().save(theEvent);\n" "}" #. Tag: para #: tutorial.xml:1060 #, no-c-format msgid "" "The servlet is now complete. A request to the servlet will be processed in a " "single <literal>Session and Transaction. As " "earlier in the standalone application, Hibernate can automatically bind " "these objects to the current thread of execution. This gives you the freedom " "to layer your code and access the <literal>SessionFactory in any " "way you like. Usually you would use a more sophisticated design and move the " "data access code into data access objects (the DAO pattern). See the " "Hibernate Wiki for more examples." msgstr "" "大功告成,这个 servlet 写完了。Hibernate 会在单一的 <literal>SessionTransaction 中处理到达的 servlet 请求。如同在" "前面的独立应用程序中那样,Hibernate 可以自动的把这些对象绑定到当前运行的线程" "中。这给了你用任何你喜欢的方式来对代码分层及访问 <literal>SessionFactory。" #. Tag: programlisting #: tutorial.xml:1082 #, fuzzy, no-c-format msgid "" "<![CDATA[\n" " <servlet-class>org.hibernate.tutorial.web.EventManagerServlet\n" " <url-pattern>/eventmanager\n" " </servlet-mapping>\n" "</web-app>]]>" msgstr "" "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<web-app version=\"2.4\"\n" " xmlns=\"http://java.sun.com/xml/ns/j2ee\"\n" " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" " xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee\n" " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">\n" "\n" " <servlet>\n" " <servlet-name>Event Manager</servlet-name>\n" " <servlet-class>events.EventManagerServlet</servlet-" "class>\n" " </servlet>\n" "\n" " <servlet-mapping>\n" " <servlet-name>Event Manager</servlet-name>\n" " <url-pattern>/eventmanager</url-pattern>\n" " </servlet-mapping>\n" "</web-app>" #. Tag: para #: tutorial.xml:1084 #, no-c-format msgid "" "To build and deploy call <literal>mvn package in your project " "directory and copy the <filename>hibernate-tutorial.war file into " "your Tomcat <filename>webapps directory." msgstr "" "在你的开发目录中,调用 <literal>ant war 来构建、打包,然后把 " "<literal>hibernate-tutorial.war 文件拷贝到你的 tomcat 的 " "<literal>webapps 目录下。假若你还没安装 Tomcat,就去下载一个,按照" "指南来安装。对此应用的发布,你不需要修改任何 Tomcat 的配置。 " #. Tag: para #: tutorial.xml:1091 #, fuzzy, no-c-format msgid "" "If you do not have Tomcat installed, download it from <ulink url=\"http://" "tomcat.apache.org/\"></ulink> and follow the installation instructions. Our " "application requires no changes to the standard Tomcat configuration." msgstr "" "如果你还没有安装 Tomcat,请从 <ulink url=\"http://tomcat.apache.org/\" /> 下" "载并按照安装说明进行安装。我们的应用程序不需要对标准的 Tomcat 配置进行修改。 " #. Tag: para #: tutorial.xml:1099 #, no-c-format msgid "" "Once deployed and Tomcat is running, access the application at " "<literal>http://localhost:8080/hibernate-tutorial/eventmanager. " "Make sure you watch the Tomcat log to see Hibernate initialize when the " "first request hits your servlet (the static initializer in " "<literal>HibernateUtil is called) and to get the detailed output " "if any exceptions occurs." msgstr "" "在部署完,启动 Tomcat 之后,通过 <literal>http://localhost:8080/hibernate-" "tutorial/eventmanager</literal> 进行访问你的应用,在第一次 servlet 请求发生" "时,请在 Tomcat log 中确认你看到 Hibernate 被初始化了" "(<literal>HibernateUtil 的静态初始化器被调用),假若有任何异常抛" "出,也可以看到详细的输出。" #. Tag: title #: tutorial.xml:1112 #, no-c-format msgid "Summary" msgstr "总结" #. Tag: para #: tutorial.xml:1114 #, no-c-format msgid "" "This tutorial covered the basics of writing a simple standalone Hibernate " "application and a small web application. More tutorials are available from " "the Hibernate <ulink url=\"http://hibernate.org\">website." msgstr "" "本章覆盖了如何编写一个简单独立的 Hibernate 命令行应用程序及小型的 Hibernate " "web 应用程序的基本要素。更多的教程可以在 <ulink url=\"http://hibernate.org" "\">website</ulink> 上找到。"

Other Hibernate examples (source code examples)

Here is a short list of links related to this Hibernate tutorial.po source code file:

Hibernate example source code file (tutorial.po)

This example Hibernate source code file (tutorial.po) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Hibernate tags/keywords

cdata, cdata, event, hibernate, hibernate, java, maven, person, sql, tag, tag, the, the, this

The Hibernate tutorial.po source code

# translation of tutorial.po to
# Xi Huang <xhuang@redhat.com>, 2006.
# Xi HUANG <xhuang@redhat.com>, 2007, 2009.
# translation of Collection_Mapping.po to
msgid ""
msgstr ""
"Project-Id-Version: tutorial\n"
"Report-Msgid-Bugs-To: http://bugs.kde.org\n"
"POT-Creation-Date: 2010-07-20 21:02+0000\n"
"PO-Revision-Date: 2010-03-16 09:56+1000\n"
"Last-Translator: Xi HUANG <xhuang@redhat.com>\n"
"Language-Team:  <en@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: KBabel 1.11.4\n"

#. Tag: title
#: tutorial.xml:34
#, no-c-format
msgid "Tutorial"
msgstr "教程"

#. Tag: para
#: tutorial.xml:36
#, no-c-format
msgid ""
"Intended for new users, this chapter provides an step-by-step introduction "
"to Hibernate, starting with a simple application using an in-memory "
"database. The tutorial is based on an earlier tutorial developed by Michael "
"Gloegl. All code is contained in the <filename>tutorials/web "
"directory of the project source."
msgstr ""
"面向新用户,从一个简单的使用内存数据库的例子开始,本章提供对 Hibernate 的逐步"
"介绍。本教程基于 Michael Gloegl 早期编写的手册。所有代码都包含在 "
"<filename>tutorials/web 目录下。"

#. Tag: para
#: tutorial.xml:45
#, no-c-format
msgid ""
"This tutorial expects the user have knowledge of both Java and SQL. If you "
"have a limited knowledge of JAVA or SQL, it is advised that you start with a "
"good introduction to that technology prior to attempting to learn Hibernate."
msgstr ""
"本教程期望用户具备 Java 和 SQL 知识。如果你这方面的知识有限,我们建议你在学"
"习 Hibernate 之前先好好了解这些技术。"

#. Tag: para
#: tutorial.xml:54
#, no-c-format
msgid ""
"The distribution contains another example application under the "
"<filename>tutorial/eg project source directory."
msgstr ""
"本版本在源代码目录 <filename>tutorial/eg 下还包含另外一个例程。"

#. Tag: title
#: tutorial.xml:62
#, no-c-format
msgid "Part 1 - The first Hibernate Application"
msgstr "第一部分 - 第一个 Hibernate 应用程序"

#. Tag: para
#: tutorial.xml:64
#, no-c-format
msgid ""
"For this example, we will set up a small database application that can store "
"events we want to attend and information about the host(s) of these events."
msgstr ""
"在这个例子里,我们将设立一个小应用程序可以保存我们希望参加的活动(events)和"
"这些活动主办方的相关信息。(译者注:在本教程的后面部分,我们将直接使用 event "
"而不是它的中文翻译“活动”,以免混淆。)"

#. Tag: para
#: tutorial.xml:70
#, no-c-format
msgid ""
"Although you can use whatever database you feel comfortable using, we will "
"use <ulink url=\"http://hsqldb.org/\">HSQLDB (an in-memory, Java "
"database) to avoid describing installation/setup of any particular database "
"servers."
msgstr ""
"虽然你可以使用任何数据库,我们还是用 <ulink url=\"http://hsqldb.org/"
"\">HSQLDB</ulink>(一个用 Java 编写的内存数据库)来避免花费篇章对数据库服务器"
"的安装/配置进行解释。"

#. Tag: title
#: tutorial.xml:79
#, no-c-format
msgid "Setup"
msgstr "设置"

#. Tag: para
#: tutorial.xml:81
#, no-c-format
msgid ""
"The first thing we need to do is to set up the development environment. We "
"will be using the \"standard layout\" advocated by alot of build tools such "
"as <ulink url=\"http://maven.org\">Maven. Maven, in particular, has "
"a good resource describing this <ulink url=\"http://maven.apache.org/guides/"
"introduction/introduction-to-the-standard-directory-layout.html\">layout</"
"ulink>. As this tutorial is to be a web application, we will be creating and "
"making use of <filename>src/main/java, src/main/"
"resources</filename> and src/main/webapp directories."
msgstr ""
"我们需要做的第一件事情是设置开发环境。我们将使用许多构建工具如 <ulink url="
"\"http://maven.org\">Maven</ulink> 所鼓吹的“标准格式”。特别是 Maven,它的资源"
"对这个<ulink url=\"http://maven.apache.org/guides/introduction/introduction-"
"to-the-standard-directory-layout.html\">格式(layout)</ulink>有着很好的描"
"述。因为本教程使用的是 web 应用程序,我么将创建和使用 <filename>src/main/"
"java</filename>、src/main/resourcessrc/"
"main/webapp</filename> 目录。"

#. Tag: para
#: tutorial.xml:91
#, no-c-format
msgid ""
"We will be using Maven in this tutorial, taking advantage of its transitive "
"dependency management capabilities as well as the ability of many IDEs to "
"automatically set up a project for us based on the maven descriptor."
msgstr ""
"在本教程里我们将使用 Maven,利用其 transitive dependency 管理以及根据 Maven "
"描述符用 IDE 自动设置项目的能力。"

#. Tag: programlisting
#: tutorial.xml:97
#, no-c-format
msgid ""
"<![CDATA[\n"
"\n"
"    <groupId>org.hibernate.tutorials\n"
"    <artifactId>hibernate-tutorial\n"
"    <version>1.0.0-SNAPSHOT\n"
"    <name>First Hibernate Tutorial\n"
"\n"
"    <build>\n"
"         <!-- we dont want the version to be part of the generated war file "
"name -->\n"
"         <finalName>${artifactId}\n"
"    </build>\n"
"\n"
"    <dependencies>\n"
"        <dependency>\n"
"            <groupId>org.hibernate\n"
"            <artifactId>hibernate-core\n"
"        </dependency>\n"
"\n"
"        <!-- Because this is a web app, we also have a dependency on the "
"servlet api. -->\n"
"        <dependency>\n"
"            <groupId>javax.servlet\n"
"            <artifactId>servlet-api\n"
"        </dependency>\n"
"\n"
"        <!-- Hibernate uses slf4j for logging, for our purposes here use the "
"simple backend -->\n"
"        <dependency>\n"
"            <groupId>org.slf4j\n"
"            <artifactId>slf4j-simple\n"
"        </dependency>\n"
"\n"
"        <!-- Hibernate gives you a choice of bytecode providers between "
"cglib and javassist -->\n"
"        <dependency>\n"
"            <groupId>javassist\n"
"            <artifactId>javassist\n"
"        </dependency>\n"
"    </dependencies>\n"
"\n"
"</project>]]>"
msgstr ""
"<![CDATA[\n"
"\n"
"    <groupId>org.hibernate.tutorials\n"
"    <artifactId>hibernate-tutorial\n"
"    <version>1.0.0-SNAPSHOT\n"
"    <name>First Hibernate Tutorial\n"
"\n"
"    <build>\n"
"         <!-- we dont want the version to be part of the generated war file "
"name -->\n"
"         <finalName>${artifactId}\n"
"    </build>\n"
"\n"
"    <dependencies>\n"
"        <dependency>\n"
"            <groupId>org.hibernate\n"
"            <artifactId>hibernate-core\n"
"        </dependency>\n"
"\n"
"        <!-- Because this is a web app, we also have a dependency on the "
"servlet api. -->\n"
"        <dependency>\n"
"            <groupId>javax.servlet\n"
"            <artifactId>servlet-api\n"
"        </dependency>\n"
"\n"
"        <!-- Hibernate uses slf4j for logging, for our purposes here use the "
"simple backend -->\n"
"        <dependency>\n"
"            <groupId>org.slf4j\n"
"            <artifactId>slf4j-simple\n"
"        </dependency>\n"
"\n"
"        <!-- Hibernate gives you a choice of bytecode providers between "
"cglib and javassist -->\n"
"        <dependency>\n"
"            <groupId>javassist\n"
"            <artifactId>javassist\n"
"        </dependency>\n"
"    </dependencies>\n"
"\n"
"</project>]]>"

#. Tag: para
#: tutorial.xml:100
#, fuzzy, no-c-format
msgid ""
"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 <ulink url=\"http://ant.apache.org/"
"ivy/\">Ivy</ulink> providing transitive dependency management you would "
"still use the dependencies mentioned below. Otherwise, you'd need to grab "
"<emphasis>all dependencies, both explicit and transitive, and add "
"them to the project's classpath. If working from the Hibernate distribution "
"bundle, this would mean <filename>hibernate3.jar, all artifacts "
"in the <filename>lib/required directory and all files from either "
"the <filename>lib/bytecode/cglib or lib/bytecode/"
"javassist</filename> directory; additionally you will need both the servlet-"
"api jar and one of the slf4j logging backends."
msgstr ""
"Maven 并不要求这样。如果你希望使用其他技术来构建这个教程(如 Ant),格式将保"
"持不变。唯一的改变是你将需要手工管理所有的依赖关系。如果你使用 <ulink url="
"\"http://ant.apache.org/ivy/\">Ivy</ulink> 来提供 transitive dependency 管"
"理,你将仍然下面提到的依赖关系。否则,你将需要找到所有的依赖关系(显性的和过"
"渡的)并把它们添加到项目的 classpath 里。如果使用 Hibernate 捆绑版本,这意味"
"着 <filename>hibernate3.jarlib/required 目"
"录下的所有 artifact 和 <filename>lib/bytecode/cglib 或 "
"<filename>lib/bytecode/javassist 下的所有文件,此外你将需要 "
"servlet-api jar 和一个 slf4j 日志后台文件。  "

#. Tag: para
#: tutorial.xml:117
#, no-c-format
msgid ""
"Save this file as <filename>pom.xml in the project root directory."
msgstr "把这个文件保存为项目根目录下的 <filename>pom.xml。"

#. Tag: title
#: tutorial.xml:124
#, no-c-format
msgid "The first class"
msgstr "第一个 class"

#. Tag: para
#: tutorial.xml:126
#, no-c-format
msgid ""
"Next, we create a class that represents the event we want to store in the "
"database; it is a simple JavaBean class with some properties:"
msgstr ""
"接下来我们创建一个类,用来代表那些我们希望储存在数据库里的 event,这是一个具"
"有一些属性的简单 JavaBean 类:"

#. Tag: programlisting
#: tutorial.xml:131
#, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial.domain;\n"
"\n"
"import java.util.Date;\n"
"\n"
"public class Event {\n"
"    private Long id;\n"
"\n"
"    private String title;\n"
"    private Date date;\n"
"\n"
"    public Event() {}\n"
"\n"
"    public Long getId() {\n"
"        return id;\n"
"    }\n"
"\n"
"    private void setId(Long id) {\n"
"        this.id = id;\n"
"    }\n"
"\n"
"    public Date getDate() {\n"
"        return date;\n"
"    }\n"
"\n"
"    public void setDate(Date date) {\n"
"        this.date = date;\n"
"    }\n"
"\n"
"    public String getTitle() {\n"
"        return title;\n"
"    }\n"
"\n"
"    public void setTitle(String title) {\n"
"        this.title = title;\n"
"    }\n"
"}]]>"
msgstr ""
"<![CDATA[package org.hibernate.tutorial.domain;\n"
"\n"
"import java.util.Date;\n"
"\n"
"public class Event {\n"
"    private Long id;\n"
"\n"
"    private String title;\n"
"    private Date date;\n"
"\n"
"    public Event() {}\n"
"\n"
"    public Long getId() {\n"
"        return id;\n"
"    }\n"
"\n"
"    private void setId(Long id) {\n"
"        this.id = id;\n"
"    }\n"
"\n"
"    public Date getDate() {\n"
"        return date;\n"
"    }\n"
"\n"
"    public void setDate(Date date) {\n"
"        this.date = date;\n"
"    }\n"
"\n"
"    public String getTitle() {\n"
"        return title;\n"
"    }\n"
"\n"
"    public void setTitle(String title) {\n"
"        this.title = title;\n"
"    }\n"
"}]]>"

#. Tag: para
#: tutorial.xml:133
#, no-c-format
msgid ""
"This class uses standard JavaBean naming conventions for property getter and "
"setter methods, as well as private visibility for the fields. Although this "
"is the recommended design, it is not required. Hibernate can also access "
"fields directly, the benefit of accessor methods is robustness for "
"refactoring."
msgstr ""
"你可以看到这个类对属性的存取方法(getter and setter method)使用了标准 "
"JavaBean 命名约定,同时把类属性(field)的访问级别设成私有的(private)。这是"
"推荐的设计,但并不是必须的。Hibernate 也可以直接访问这些 field,而使用访问方"
"法(accessor method)的好处是提供了重构时的健壮性(robustness)。"

#. Tag: para
#: tutorial.xml:141
#, no-c-format
msgid ""
"The <literal>id property holds a unique identifier value for a "
"particular event. All persistent entity classes (there are less important "
"dependent classes as well) will need such an identifier property if we want "
"to use the full feature set of Hibernate. In fact, most applications, "
"especially web applications, need to distinguish objects by identifier, so "
"you should consider this a feature rather than a limitation. However, we "
"usually do not manipulate the identity of an object, hence the setter method "
"should be private. Only Hibernate will assign identifiers when an object is "
"saved. Hibernate can access public, private, and protected accessor methods, "
"as well as public, private and protected fields directly. The choice is up "
"to you and you can match it to fit your application design."
msgstr ""
"对一特定的 event, <literal>id 属性持有唯一??标识符(identifier)的"
"值。如果我们希望使用 Hibernate 提供的所有特性,那么所有的持久化实体"
"(persistent entity)类(这里也包括一些次要依赖类)都需要一个这样的标识符属"
"性。而事实上,大多数应用程序(特别是 web 应用程序)都需要通过标识符来区别对"
"象,所以你应该考虑使用标识符属性而不是把它当作一种限制。然而,我们通常不会操"
"作对象的标识(identity),因此它的 setter 方法的访问级别应该声明 private。这"
"样当对象被保存的时候,只有 Hibernate 可以为它分配标识符值。你可看到Hibernate"
"可以直接访问 public,private 和 protected 的访问方法和 field。所以选择哪种方"
"式完全取决于你,你可以使你的选择与你的应用程序设计相吻合。 "

#. Tag: para
#: tutorial.xml:156
#, no-c-format
msgid ""
"The no-argument constructor is a requirement for all persistent classes; "
"Hibernate has to create objects for you, using Java Reflection. The "
"constructor can be private, however package or public visibility is required "
"for runtime proxy generation and efficient data retrieval without bytecode "
"instrumentation."
msgstr ""
"所有的持久化类(persistent classes)都要求有无参的构造器,因为 Hibernate 必须"
"使用 Java 反射机制来为你创建对象。构造器(constructor)的访问级别可以是 "
"private,然而当生成运行时代理(runtime proxy)的时候则要求使用至少是 package "
"级别的访问控制,这样在没有字节码指令(bytecode instrumentation)的情况下,从"
"持久化类里获取数据会更有效率。 "

#. Tag: para
#: tutorial.xml:164
#, no-c-format
msgid ""
"Save this file to the <filename>src/main/java/org/hibernate/tutorial/domain"
msgstr ""
"<![CDATA["

#. Tag: para
#: tutorial.xml:187
#, no-c-format
msgid ""
"Hibernate DTD is sophisticated. You can use it for auto-completion of XML "
"mapping elements and attributes in your editor or IDE. Opening up the DTD "
"file in your text editor is the easiest way to get an overview of all "
"elements and attributes, and to view the defaults, as well as some comments. "
"Hibernate will not load the DTD file from the web, but first look it up from "
"the classpath of the application. The DTD file is included in "
"<filename>hibernate-core.jar (it is also included in the "
"<filename>hibernate3.jar, if using the distribution bundle)."
msgstr ""
"注意 Hibernate 的 DTD 是非常复杂的。你的编辑器或者 IDE 里使用它来自动完成那些"
"用来映射的 XML 元素(element)和属性(attribute)。你也可以在文本编辑器里打"
"开 DTD — 这是最简单的方式来概览所有的元素和 attribute,并查看它们的缺省值以及"
"注释。注意 Hibernate 不会从 web 加载 DTD 文件,但它会首先在应用程序的 "
"classpath 中查找。DTD 文件已包括在 <literal>hibernate3.jar 里,同时"
"也在 Hibernate 发布包的 <literal>src/ 目录下。 "

#. Tag: para
#: tutorial.xml:200
#, no-c-format
msgid ""
"We will omit the DTD declaration in future examples to shorten the code. It "
"is, of course, not optional."
msgstr ""
"为缩短代码长度,在以后的例子里我们会省略 DTD 的声明。当然,在实际的应用程序"
"中,DTD 声明是必需的。 "

#. Tag: para
#: tutorial.xml:206
#, no-c-format
msgid ""
"Between the two <literal>hibernate-mapping tags, include a "
"<literal>class element. All persistent entity classes (again, "
"there might be dependent classes later on, which are not first-class "
"entities) need a mapping to a table in the SQL database:"
msgstr ""
"在 <literal>hibernate-mapping 标签(tag)之间, 含有一个 "
"<literal>class 元素。所有的持久化实体类(再次声明,或许接下来会有依"
"赖类,就是那些次要的实体)都需要一个这样的映射,来把类对象映射到 SQL 数据库里"
"的表:"

#. Tag: programlisting
#: tutorial.xml:213
#, no-c-format
msgid ""
"<![CDATA["
msgstr ""
"<![CDATA["

#. Tag: para
#: tutorial.xml:215
#, no-c-format
msgid ""
"So far we have told Hibernate how to persist and load object of class "
"<literal>Event to the table EVENTS. Each "
"instance is now represented by a row in that table. Now we can continue by "
"mapping the unique identifier property to the tables primary key. As we do "
"not want to care about handling this identifier, we configure Hibernate's "
"identifier generation strategy for a surrogate primary key column:"
msgstr ""
"到目前为止,我们告诉了 Hibernate 怎样把 <literal>Events 类的对象持"
"久化到数据库的 <literal>EVENTS 表里,以及怎样从 EVENTSEvents 类的对象。每个实例对应着数据库表"
"中的一行。现在我们将继续讨论有关唯一标识符属性到数据库表的映射。另外,由于我"
"们不关心怎样处理这个标识符,我们就配置由 Hibernate 的标识符生成策略来产生代理"
"主键字段:"

#. Tag: programlisting
#: tutorial.xml:225
#, no-c-format
msgid ""
"<![CDATA["
msgstr ""
"<![CDATA["

#. Tag: para
#: tutorial.xml:227
#, no-c-format
msgid ""
"The <literal>id element is the declaration of the identifier "
"property. The <literal>name=\"id\" mapping attribute declares the "
"name of the JavaBean property and tells Hibernate to use the <literal>getId()"
"</literal> and setId() methods to access the property. "
"The column attribute tells Hibernate which column of the <literal>EVENTS 元素是对 identifier 属性的声明。name=\"id\"setId() 方法来访问这个属性。"
"column 属性告诉 Hibernate  <literal>EVENTS 表的哪个字段持有主键值。"

#. Tag: para
#: tutorial.xml:237
#, no-c-format
msgid ""
"The nested <literal>generator element specifies the identifier "
"generation strategy (aka how are identifier values generated?). In this case "
"we choose <literal>native, which offers a level of portability "
"depending on the configured database dialect. Hibernate supports database "
"generated, globally unique, as well as application assigned, identifiers. "
"Identifier value generation is also one of Hibernate's many extension points "
"and you can plugin in your own strategy."
msgstr ""
"嵌套的 <literal>generator 元素指定标识符的生成策略(也就是标识符值"
"是怎么产生的)。在这个例子里,我们选择 <literal>native,它提供了取"
"决于数据库方言的可移植性。Hibernate 数据库生成的、全局性唯一的以及应用程序分"
"配的标识符。标识符值的生成也是 Hibernate 的扩展功能之一,你可以插入自己的策"
"略。"

#. Tag: para
#: tutorial.xml:249
#, fuzzy, no-c-format
msgid ""
"<literal>native is no longer consider the best strategy in terms "
"of portability. for further discussion, see"
msgstr ""
"从移植性来说,<literal>native 不再被认为是最好的策略。进一步的讨"
"论,请参考 <xref linkend=\"portability-idgen\" />。 "

#. Tag: para
#: tutorial.xml:255
#, no-c-format
msgid ""
"Lastly, we need to tell Hibernate about the remaining entity class "
"properties. By default, no properties of the class are considered persistent:"
msgstr ""
"最后我们在映射文件里面包含需要持久化属性的声明。默认情况下,类里面的属性都被"
"视为非持久化的: "

#. Tag: programlisting
#: tutorial.xml:261
#, no-c-format
msgid ""
"<![CDATA[\n"
"<hibernate-mapping package=\"org.hibernate.tutorial.domain\">\n"
"\n"
"    <class name=\"Event\" table=\"EVENTS\">\n"
"        <id name=\"id\" column=\"EVENT_ID\">\n"
"            <generator class=\"native\"/>\n"
"        </id>\n"
"        <property name=\"date\" type=\"timestamp\" column=\"EVENT_DATE\"/>\n"
"        <property name=\"title\"/>\n"
"    </class>\n"
"\n"
"</hibernate-mapping>]]>"
msgstr ""
"<![CDATA[\n"
"<hibernate-mapping package=\"org.hibernate.tutorial.domain\">\n"
"\n"
"    <class name=\"Event\" table=\"EVENTS\">\n"
"        <id name=\"id\" column=\"EVENT_ID\">\n"
"            <generator class=\"native\"/>\n"
"        </id>\n"
"        <property name=\"date\" type=\"timestamp\" column=\"EVENT_DATE\"/>\n"
"        <property name=\"title\"/>\n"
"    </class>\n"
"\n"
"</hibernate-mapping>]]>"

#. Tag: para
#: tutorial.xml:263
#, no-c-format
msgid ""
"Similar to the <literal>id element, the name "
"attribute of the <literal>property element tells Hibernate which "
"getter and setter methods to use. In this case, Hibernate will search for "
"<literal>getDate(), setDate(), getTitle"
"()</literal> and setTitle() methods."
msgstr ""
"和 <literal>id 元素一样,property 元素的 "
"<literal>name 属性告诉 Hibernate 使用哪个 getter 和 setter 方法。在"
"此例中,Hibernate 会寻找 <literal>getDate()、setDate()getTitle()setTitle() 方"
"法。 "

#. Tag: para
#: tutorial.xml:274
#, no-c-format
msgid ""
"Why does the <literal>date property mapping include the "
"<literal>column attribute, but the title does "
"not? Without the <literal>column attribute, Hibernate by default "
"uses the property name as the column name. This works for <literal>titledate is a reserved keyword in most "
"databases so you will need to map it to a different name."
msgstr ""
"为什么 <literal>date 属性的映射含有 column "
"attribute,而 <literal>title 却没有?当没有设定 column,这样工作得很好。然而,date "
"在多数的数据库里,是一个保留关键字,所以我们最好把它映射成一个不同的名字。 "

#. Tag: para
#: tutorial.xml:284
#, no-c-format
msgid ""
"The <literal>title mapping also lacks a type "
"attribute. The types declared and used in the mapping files are not Java "
"data types; they are not SQL database types either. These types are called "
"<emphasis>Hibernate mapping types, converters which can translate "
"from Java to SQL data types and vice versa. Again, Hibernate will try to "
"determine the correct conversion and mapping type itself if the "
"<literal>type attribute is not present in the mapping. In some "
"cases this automatic detection using Reflection on the Java class might not "
"have the default you expect or need. This is the case with the "
"<literal>date property. Hibernate cannot know if the property, "
"which is of <literal>java.util.Date, should map to a SQL "
"<literal>date, timestamp, or time converter."
msgstr ""
"另一有趣的事情是 <literal>title 属性缺少一个 type,它们能把 Java 数据"
"类型转换到 SQL 数据类型,反之亦然。再次重申,如果在映射文件中没有设置 "
"<literal>type 属性的话,Hibernate 会自己试着去确定正确的转换类型和"
"它的映射类型。在某些情况下这个自动检测机制(在 Java 类上使用反射机制)不会产"
"生你所期待或需要的缺省值。<literal>date 属性就是个很好的例子,"
"Hibernate 无法知道这个属性(<literal>java.util.Date 类型的)应该被"
"映射成:SQL <literal>date,或 timestamp,还是 "
"<literal>time 字段。在此例中,把这个属性映射成 timestamp 目录 - 这是 HSQL DB 存储数"
"据文件的地方。此时在 data 目录中运行 <literal>java -classpath ../lib/hsqldb."
"jar org.hsqldb.Server</literal> 就可启动数据库。你可以在 log 中看到它的启动,"
"及绑定到 TCP/IP 套接字,这正是我们的应用程序稍后会连接的地方。如果你希望在本"
"例中运行一个全新的数据库,就在窗口中按下 <literal>CTRL + C 来关闭 "
"HSQL 数据库,并删除 <literal>data/ 目录下的所有文件,再重新启动 "
"HSQL 数据库。 "

#. Tag: para
#: tutorial.xml:340
#, no-c-format
msgid ""
"Hibernate will be connecting to the database on behalf of your application, "
"so it needs to know how to obtain connections. For this tutorial we will be "
"using a standalone connection pool (as opposed to a <interfacename>javax.sql."
"DataSource</interfacename>). Hibernate comes with support for two third-"
"party open source JDBC connection pools: <ulink url=\"https://sourceforge."
"net/projects/c3p0\">c3p0</ulink> and . However, we will be using the Hibernate built-in "
"connection pool for this tutorial."
msgstr ""
"Hibernate 将为你的应用程序连接到数据库,所以它需要知道如何获取连接。在这个教"
"程里,我们使用一个独立连接池(和 <interfacename>javax.sql.DataSource。然而,在本教程里我们将使"
"用 Hibernate 内置的连接池。"

#. Tag: para
#: tutorial.xml:351
#, no-c-format
msgid ""
"The built-in Hibernate connection pool is in no way intended for production "
"use. It lacks several features found on any decent connection pool."
msgstr "嵌入的 Hibernate 连接池不用于产品环境。它缺乏连接池里的几个功能。"

#. Tag: para
#: tutorial.xml:357
#, no-c-format
msgid ""
"For Hibernate's configuration, we can use a simple <literal>hibernate."
"properties</literal> file, a more sophisticated hibernate.cfg.xmlhibernate.cfg.xml\n"
"        <property name=\"connection.password\">\n"
"\n"
"        <!-- JDBC connection pool (use the built-in) -->\n"
"        <property name=\"connection.pool_size\">1\n"
"\n"
"        <!-- SQL dialect -->\n"
"        <property name=\"dialect\">org.hibernate.dialect.HSQLDialect\n"
"\n"
"        <!-- Disable the second-level cache  -->\n"
"        <property name=\"cache.provider_class\">org.hibernate.cache."
"NoCacheProvider</property>\n"
"\n"
"        <!-- Echo all executed SQL to stdout -->\n"
"        <property name=\"show_sql\">true\n"
"\n"
"        <!-- Drop and re-create the database schema on startup -->\n"
"        <property name=\"hbm2ddl.auto\">update\n"
"\n"
"        <mapping resource=\"org/hibernate/tutorial/domain/Event.hbm.xml\"/>\n"
"\n"
"    </session-factory>\n"
"\n"
"</hibernate-configuration>]]>"
msgstr ""
"<![CDATA[\n"
"        <property name=\"connection.password\">\n"
"\n"
"        <!-- JDBC connection pool (use the built-in) -->\n"
"        <property name=\"connection.pool_size\">1\n"
"\n"
"        <!-- SQL dialect -->\n"
"        <property name=\"dialect\">org.hibernate.dialect.HSQLDialect\n"
"\n"
"        <!-- Disable the second-level cache  -->\n"
"        <property name=\"cache.provider_class\">org.hibernate.cache."
"NoCacheProvider</property>\n"
"\n"
"        <!-- Echo all executed SQL to stdout -->\n"
"        <property name=\"show_sql\">true\n"
"\n"
"        <!-- Drop and re-create the database schema on startup -->\n"
"        <property name=\"hbm2ddl.auto\">update\n"
"\n"
"        <mapping resource=\"org/hibernate/tutorial/domain/Event.hbm.xml\"/>\n"
"\n"
"    </session-factory>\n"
"\n"
"</hibernate-configuration>]]>"

#. Tag: para
#: tutorial.xml:366
#, no-c-format
msgid "Notice that this configuration file specifies a different DTD"
msgstr "请注意,这个配置文件指定了一个不同的 DTD。"

#. Tag: para
#: tutorial.xml:369
#, no-c-format
msgid ""
"You configure Hibernate's <literal>SessionFactory. SessionFactory "
"is a global factory responsible for a particular database. If you have "
"several databases, for easier startup you should use several <literal><"
"session-factory></literal> configurations in several configuration files."
msgstr ""
"注意这个 XML 配置使用了一个不同的 DTD。在这里,我们配置了 Hibernate 的"
"<literal>SessionFactory — 一个关联于特定数据库全局的工厂"
"(factory)。如果你要使用多个数据库,就要用多个的 <literal><session-"
"factory></literal>,通常把它们放在多个配置文件中(为了更容易启动)。 "

#. Tag: para
#: tutorial.xml:376
#, no-c-format
msgid ""
"The first four <literal>property elements contain the necessary "
"configuration for the JDBC connection. The dialect <literal>property 元素包含了 JDBC 连接所必需的配置。方言 "
"<literal>property 元素指定了 Hibernate 生成的特定 SQL 语句。"

#. Tag: para
#: tutorial.xml:383
#, fuzzy, no-c-format
msgid ""
"In most cases, Hibernate is able to properly determine which dialect to use. "
"See <xref linkend=\"portability-dialectresolver\"/> for more information."
msgstr ""
"在大多数情况下,Hibernate 都能够正确地决定所使用的方言。更多信息请参考 <xref "
"linkend=\"portability-dialectresolver\" />。 "

#. Tag: para
#: tutorial.xml:389
#, no-c-format
msgid ""
"Hibernate's automatic session management for persistence contexts is "
"particularly useful in this context. The <literal>hbm2ddl.auto "
"option turns on automatic generation of database schemas directly into the "
"database. This can also be turned off by removing the configuration option, "
"or redirected to a file with the help of the <literal>SchemaExport "
"Ant task. Finally, add the mapping file(s) for persistent classes to the "
"configuration."
msgstr ""
"最开始的 4 个 <literal>property 元素包含必要的 JDBC 连接信息。方言"
"(dialect)的 <literal>property 元素指明 Hibernate 生成的特定 SQL "
"变量。你很快会看到,Hibernate 对持久化上下文的自动 session 管理就会派上用"
"场。 打开 <literal>hbm2ddl.auto 选项将自动生成数据库模式(schema)"
"- 直接加入数据库中。当然这个选项也可以被关闭(通过去除这个配置选项)或者通"
"过 Ant 任务 <literal>SchemaExport 的帮助来把数据库 schema 重定向到"
"文件中。最后,在配置中为持久化类加入映射文件。 "

#. Tag: para
#: tutorial.xml:398
#, no-c-format
msgid ""
"Save this file as <filename>hibernate.cfg.xml into the "
"<filename>src/main/resources directory."
msgstr ""
"把这个文件保存为 <filename>src/main/resources 目录下的 "
"<filename>hibernate.cfg.xml。"

#. Tag: title
#: tutorial.xml:406
#, no-c-format
msgid "Building with Maven"
msgstr "用 Maven 构建  "

#. Tag: para
#: tutorial.xml:408
#, no-c-format
msgid ""
"We will now build the tutorial with Maven. You will need to have Maven "
"installed; it is available from the <ulink url=\"http://maven.apache.org/"
"download.html\">Maven download page</ulink>. Maven will read the /"
"pom.xml</filename> file we created earlier and know how to perform some "
"basic project tasks. First, lets run the <literal>compile goal to "
"make sure we can compile everything so far:"
msgstr ""
"我们将用 Maven 构建这个教程。你将需要安装 Maven;你可以从 <ulink url="
"\"http://maven.apache.org/download.html\">Maven 下载页面</ulink>获得 Maven。"
"Maen 将读取我们先前创建的 <filename>/pom.xml 并知道执行基本的项目"
"任务。首先,让我们运行 <literal>compile 目标来确保我们可以编译到目"
"前为止的所有程序:"

#. Tag: programlisting
#: tutorial.xml:418
#, no-c-format
msgid ""
"<![CDATA[[hibernateTutorial]$ mvn compile\n"
"[INFO] Scanning for projects...\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] Building First Hibernate Tutorial\n"
"[INFO]    task-segment: [compile]\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] [resources:resources]\n"
"[INFO] Using default encoding to copy filtered resources.\n"
"[INFO] [compiler:compile]\n"
"[INFO] Compiling 1 source file to /home/steve/projects/sandbox/"
"hibernateTutorial/target/classes\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] BUILD SUCCESSFUL\n"
"[INFO] "
"------------------------------------------------------------------------\n"
"[INFO] Total time: 2 seconds\n"
"[INFO] Finished at: Tue Jun 09 12:25:25 CDT 2009\n"
"[INFO] Final Memory: 5M/547M\n"
"[INFO] "
"------------------------------------------------------------------------]]>"
msgstr ""

#. Tag: title
#: tutorial.xml:423
#, no-c-format
msgid "Startup and helpers"
msgstr "启动和辅助类"

#. Tag: para
#: tutorial.xml:425
#, no-c-format
msgid ""
"It is time to load and store some <literal>Event objects, but "
"first you have to complete the setup with some infrastructure code. You have "
"to startup Hibernate by building a global <interfacename>org.hibernate."
"SessionFactory</interfacename> object and storing it somewhere for easy "
"access in application code. A <interfacename>org.hibernate.SessionFactoryorg.hibernate.Sessionorg.hibernate.Session is a thread-safe "
"global object that is instantiated once."
msgstr ""
"是时候来加载和储存一些 <literal>Event 对象了,但首先我们得编写一些"
"基础的代码以完成设置。我们必须启动 Hibernate,此过程包括创建一个全局的 "
"<literal>SessoinFactory,并把它储存在应用程序代码容易访问的地方。"
"<literal>SessionFactory 可以创建并打开新的 SessionSession 代表一个单线程的单元操作,"
"<interfacename>org.hibernate.SessionFactory 则是个线程安全的"
"全局对象,只需要被实例化一次。 "

#. Tag: para
#: tutorial.xml:439
#, no-c-format
msgid ""
"We will create a <literal>HibernateUtil helper class that takes "
"care of startup and makes accessing the <interfacename>org.hibernate."
"SessionFactory</interfacename> more convenient."
msgstr ""
"我们将创建一个 <literal>HibernateUtil 辅助类(helper class)来负责"
"启动 Hibernate 和更方便地操作 <interfacename>org.hibernate.SessionFactory "
"reference from JNDI in an application server or any other location for that "
"matter."
msgstr ""
"这个类不但在它的静态初始化过程(仅当加载这个类的时候被 JVM 执行一次)中产生全"
"局的 <interfacename>org.hibernate.SessionFactory,而且隐藏了"
"它使用了静态 singleton 的事实。它也可能在应用程序服务器中的 JNDI 查找 "
"<interfacename>org.hibernate.SessionFactory。"

#. Tag: para
#: tutorial.xml:461
#, no-c-format
msgid ""
"If you give the <interfacename>org.hibernate.SessionFactory "
"a name in your configuration, Hibernate will try to bind it to JNDI under "
"that name after it has been built. Another, better option is to use a JMX "
"deployment and let the JMX-capable container instantiate and bind a "
"<literal>HibernateService to JNDI. Such advanced options are "
"discussed later."
msgstr ""
"如果你在配置文件中给 <interfacename>org.hibernate.SessionFactory 并把它绑定到 JNDI。这些高级可选项在后面的"
"章节中会讨论到。"

#. Tag: para
#: tutorial.xml:470
#, no-c-format
msgid ""
"You now need to configure a logging system. Hibernate uses commons logging "
"and provides two choices: Log4j and JDK 1.4 logging. Most developers prefer "
"Log4j: copy <literal>log4j.properties from the Hibernate "
"distribution in the <literal>etc/ directory to your srchibernate.cfg.xml. If you "
"prefer to have more verbose output than that provided in the example "
"configuration, you can change the settings. By default, only the Hibernate "
"startup message is shown on stdout."
msgstr ""
"再次编译这个应用程序应该不会有问题。最后我们需要配置一个日志(logging)系统 — "
"Hibernate 使用通用日志接口,允许你在 Log4j 和 JDK 1.4 日志之间进行选择。多数"
"开发者更喜欢 Log4j:从 Hibernate 的发布包中(它在 <literal>etc/ 目"
"录下)拷贝 <literal>log4j.properties 到你的 src "
"目录,与 <literal>hibernate.cfg.xml 放在一起。看一下配置示例,如果"
"你希望看到更加详细的输出信息,你可以修改配置。默认情况下,只有 Hibernate 的启"
"动信息才会显示在标准输出上。 "

#. Tag: para
#: tutorial.xml:480
#, no-c-format
msgid ""
"The tutorial infrastructure is complete and you are now ready to do some "
"real work with Hibernate."
msgstr "示例的基本框架完成了 — 现在我们可以用 Hibernate 来做些真正的工作。 "

#. Tag: title
#: tutorial.xml:488
#, no-c-format
msgid "Loading and storing objects"
msgstr "加载并存储对象"

#. Tag: para
#: tutorial.xml:490
#, fuzzy, no-c-format
msgid ""
"We are now ready to start doing some real work with Hibernate. Let's start "
"by writing an <literal>EventManager class with a main()EventManager 类: "

#. Tag: programlisting
#: tutorial.xml:496
#, fuzzy, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial;\n"
"\n"
"import org.hibernate.Session;\n"
"\n"
"import java.util.*;\n"
"\n"
"import org.hibernate.tutorial.domain.Event;\n"
"import org.hibernate.tutorial.util.HibernateUtil;\n"
"\n"
"public class EventManager {\n"
"\n"
"    public static void main(String[] args) {\n"
"        EventManager mgr = new EventManager();\n"
"\n"
"        if (args[0].equals(\"store\")) {\n"
"            mgr.createAndStoreEvent(\"My Event\", new Date());\n"
"        }\n"
"\n"
"        HibernateUtil.getSessionFactory().close();\n"
"    }\n"
"\n"
"    private void createAndStoreEvent(String title, Date theDate) {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"\n"
"        Event theEvent = new Event();\n"
"        theEvent.setTitle(title);\n"
"        theEvent.setDate(theDate);\n"
"        session.save(theEvent);\n"
"\n"
"        session.getTransaction().commit();\n"
"    }\n"
"\n"
"}]]>"
msgstr ""
"package events;\n"
"import org.hibernate.Session;\n"
"\n"
"import java.util.Date;\n"
"\n"
"import util.HibernateUtil;\n"
"\n"
"public class EventManager {\n"
"\n"
"    public static void main(String[] args) {\n"
"        EventManager mgr = new EventManager();\n"
"\n"
"        if (args[0].equals(\"store\")) {\n"
"            mgr.createAndStoreEvent(\"My Event\", new Date());\n"
"        }\n"
"\n"
"        HibernateUtil.getSessionFactory().close();\n"
"    }\n"
"\n"
"    private void createAndStoreEvent(String title, Date theDate) {\n"
"\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"\n"
"        session.beginTransaction();\n"
"\n"
"        Event theEvent = new Event();\n"
"        theEvent.setTitle(title);\n"
"        theEvent.setDate(theDate);\n"
"\n"
"        session.save(theEvent);\n"
"\n"
"        session.getTransaction().commit();\n"
"    }\n"
"\n"
"}"

#. Tag: para
#: tutorial.xml:498
#, no-c-format
msgid ""
"In <literal>createAndStoreEvent() we created a new Event on the "
"database."
msgstr ""
"在 <literal>createAndStoreEvent() 来里我们创建了一个新的 "
"<literal>Event 对象并把它传递给 Hibernate。现在 Hibernate 负责与 "
"SQL 打交道,并把 <literal>INSERT 命令传给数据库。"

#. Tag: para
#: tutorial.xml:505
#, fuzzy, no-c-format
msgid ""
"A <interface>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 <interface>org.hibernate.Session and a database "
"transaction. To shield our code from the actual underlying transaction "
"system we use the Hibernate <interfacename>org.hibernate.Transaction 就是个单一的工作单元。我们"
"暂时让事情简单一些,并假设 Hibernate <interface>org.hibernate.Session do? First, "
"you can call it as many times and anywhere you like once you get hold of "
"your <interfacename>org.hibernate.SessionFactory. The "
"<literal>getCurrentSession() method always returns the \"current\" "
"unit of work. Remember that we switched the configuration option for this "
"mechanism to \"thread\" in our <filename>src/main/resources/hibernate.cfg."
"xml</filename>? Due to that setting, the context of a current unit of work "
"is bound to the current Java thread that executes the application."
msgstr ""
"<literal>sessionFactory.getCurrentSession() 是干什么的呢?首先,只"
"要你持有 <interfacename>org.hibernate.SessionFactory,大可在"
"任何时候、任何地点调用这个方法。<literal>getCurrentSession() 方法总"
"会返回“当前的”工作单元。记得我们在 <filename>src/main/resources/hibernate."
"cfg.xml</filename> 中把这一配置选项调整为 \"thread\" 了吗?因此,因此,当前工"
"作单元被绑定到当前执行我们应用程序的 Java 线程。但是,这并非是完全准确的,你还"
"得考虑工作单元的生命周期范围(scope),它何时开始,又何时结束。"

#. Tag: para
#: tutorial.xml:532
#, no-c-format
msgid ""
"Hibernate offers three methods of current session tracking. The \"thread\" "
"based method is not intended for production use; it is merely useful for "
"prototyping and tutorials such as this one. Current session tracking is "
"discussed in more detail later on."
msgstr ""
"Hibernate 提供三种跟踪当前会话的方法。基于“线程”的方法不适合于产品环境,它仅"
"用于 prototyping 和教学用途。后面将更详细地讨论会话跟踪。"

#. Tag: para
#: tutorial.xml:541
#, no-c-format
msgid ""
"A <interface>org.hibernate.Session begins when the first call to "
"<literal>getCurrentSession() is made for the current thread. It is "
"then bound by Hibernate to the current thread. When the transaction ends, "
"either through commit or rollback, Hibernate automatically unbinds the "
"<interface>org.hibernate.Session from the thread and closes it "
"for you. If you call <literal>getCurrentSession() again, you get a "
"new <interface>org.hibernate.Session and can start a new unit of "
"work."
msgstr ""
"<interface>org.hibernate.Session 在第一次被使用的时候,即第一次调"
"用 <literal>getCurrentSession() 的时候,其生命周期就开始。然后它被 "
"Hibernate 绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate 会"
"自动把 <interface>org.hibernate.Session 从当前线程剥离,并且关闭"
"它。假若你再次调用 <literal>getCurrentSession(),你会得到一个新的 "
"<interface>org.hibernate.Session,并且开始一个新的工作单元。"

#. Tag: para
#: tutorial.xml:554
#, no-c-format
msgid ""
"Related to the unit of work scope, should the Hibernate <interface>org."
"hibernate.Session</interface> be used to execute one or several database "
"operations? The above example uses one <interface>org.hibernate.Session is flexible but you "
"should never design your application to use a new Hibernate <interface>org."
"hibernate.Session</interface> for every database "
"operation. Even though it is used in the following examples, consider "
"<emphasis>session-per-operation an anti-pattern. A real web "
"application is shown later in the tutorial which will help illustrate this."
msgstr ""
"和工作单元的生命周期这个话题相关,Hibernate <interface>org.hibernate."
"Session</interface> 是否被应该用来执行多次数据库操作?上面的例子对每一次操作"
"使用了一个 <interface>org.hibernate.Session,这完全是巧合,这个例"
"子不是很复杂,无法展示其他方式。Hibernate <interface>org.hibernate.Session"
"每一次</emphasis>数据库操作都用一个新的 Hibernate org.hibernate."
"Session</interface>。因此就算下面的例子(它们都很简单)中你可以看到这种用法,"
"记住<emphasis>每次操作一个 session 是一个反模式。在本教程的后面会"
"展示一个真正的(web)程序。"

#. Tag: para
#: tutorial.xml:571
#, fuzzy, no-c-format
msgid ""
"See <xref linkend=\"transactions\"/> for more information about transaction "
"handling and demarcation. The previous example also skipped any error "
"handling and rollback."
msgstr ""
"关于事务处理及事务边界界定的详细信息,请参看 <xref linkend=\"transactions\" /"
"> 。在上面的例子中,我们也忽略了所有的错误与回滚的处理。 "

#. Tag: para
#: tutorial.xml:577
#, no-c-format
msgid ""
"To run this, we will make use of the Maven exec plugin to call our class "
"with the necessary classpath setup: <command>mvn exec:java -Dexec.mainClass="
"\"org.hibernate.tutorial.EventManager\" -Dexec.args=\"store\"</command>"
msgstr ""
"要运行它,我们将使用 Maven exec 插件以及必要的 classpath 设置来进行调用:"
"<command>mvn exec:java -Dexec.mainClass=\"org.hibernate.tutorial.EventManager"
"\" -Dexec.args=\"store\"</command>。"

#. Tag: para
#: tutorial.xml:584
#, no-c-format
msgid "You may need to perform <command>mvn compile first."
msgstr "你可能需要先执行 <command>mvn compile。"

#. Tag: para
#: tutorial.xml:589
#, no-c-format
msgid ""
"You should see Hibernate starting up and, depending on your configuration, "
"lots of log output. Towards the end, the following line will be displayed:"
msgstr ""
"你应该会看到,编译以后,Hibernate 根据你的配置启动,并产生一大堆的输出日志。"
"在日志最后你会看到下面这行: "

#. Tag: programlisting
#: tutorial.xml:594
#, fuzzy, no-c-format
msgid ""
"<![CDATA[[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) "
"values (?, ?, ?)]]>"
msgstr ""
"[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values "
"(?, ?, ?)"

#. Tag: para
#: tutorial.xml:596
#, no-c-format
msgid "This is the <literal>INSERT executed by Hibernate."
msgstr "执行 HQL <literal>INSERT 语句的例子如下: "

#. Tag: para
#: tutorial.xml:600
#, no-c-format
msgid "To list stored events an option is added to the main method:"
msgstr ""
"我们想要列出所有已经被存储的 events,就要增加一个条件分支选项到 main 方法中:"

#. Tag: programlisting
#: tutorial.xml:604
#, fuzzy, no-c-format
msgid ""
"<![CDATA[        if (args[0].equals(\"store\")) {\n"
"            mgr.createAndStoreEvent(\"My Event\", new Date());\n"
"        }\n"
"        else if (args[0].equals(\"list\")) {\n"
"            List events = mgr.listEvents();\n"
"            for (int i = 0; i < events.size(); i++) {\n"
"                Event theEvent = (Event) events.get(i);\n"
"                System.out.println(\n"
"                        \"Event: \" + theEvent.getTitle() + \" Time: \" + "
"theEvent.getDate()\n"
"                );\n"
"            }\n"
"        }]]>"
msgstr ""
"if (args[0].equals(\"store\")) {\n"
"    mgr.createAndStoreEvent(\"My Event\", new Date());\n"
"}\n"
"else if (args[0].equals(\"list\")) {\n"
"    List events = mgr.listEvents();\n"
"    for (int i = 0; i < events.size(); i++) {\n"
"        Event theEvent = (Event) events.get(i);\n"
"        System.out.println(\"Event: \" + theEvent.getTitle() +\n"
"                           \" Time: \" + theEvent.getDate());\n"
"    }\n"
"}"

#. Tag: para
#: tutorial.xml:606
#, no-c-format
msgid "A new <literal>listEvents() method is also added:"
msgstr "我们也增加一个新的 <literal>listEvents() 方法: "

#. Tag: programlisting
#: tutorial.xml:610
#, fuzzy, no-c-format
msgid ""
"<![CDATA[    private List listEvents() {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"        List result = session.createQuery(\"from Event\").list();\n"
"        session.getTransaction().commit();\n"
"        return result;\n"
"    }]]>"
msgstr ""
"private List listEvents() {\n"
"\n"
"    Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"\n"
"    session.beginTransaction();\n"
"\n"
"    List result = session.createQuery(\"from Event\").list();\n"
"\n"
"    session.getTransaction().commit();\n"
"\n"
"    return result;\n"
"}"

#. Tag: para
#: tutorial.xml:612
#, fuzzy, no-c-format
msgid ""
"Here, we are using a Hibernate Query Language (HQL) query to load all "
"existing <literal>Event objects from the database. Hibernate will "
"generate the appropriate SQL, send it to the database and populate "
"<literal>Event objects with the data. You can create more complex "
"queries with HQL. See <xref linkend=\"queryhql\"/> for more information."
msgstr ""
"我们在这里是用一个 HQL(Hibernate Query Language-Hibernate查询语言)查询语句"
"来从数据库中加载所有存在的 <literal>Event 对象。Hibernate 会生成适"
"当的 SQL,把它发送到数据库,并操作从查询得到数据的 <literal>Event "
"对象。当然,你可以使用 HQL 来创建更加复杂的查询。更多信息请参考 <xref "
"linkend=\"queryhql\"/>。 "

#. Tag: para
#: tutorial.xml:620
#, no-c-format
msgid ""
"Now we can call our new functionality, again using the Maven exec plugin: "
"<command>mvn exec:java -Dexec.mainClass=\"org.hibernate.tutorial.EventManager"
"\" -Dexec.args=\"list\"</command>"
msgstr ""
"现在我们可以再次用 Maven exec plugin - <command>mvn exec:java -Dexec."
"mainClass=\"org.hibernate.tutorial.EventManager\" -Dexec.args=\"list\"</"
"command> 调用新的功能了。"

#. Tag: title
#: tutorial.xml:630
#, no-c-format
msgid "Part 2 - Mapping associations"
msgstr "第二部分 - 关联映射"

#. Tag: para
#: tutorial.xml:632
#, no-c-format
msgid ""
"So far we have mapped a single persistent entity class to a table in "
"isolation. Let's expand on that a bit and add some class associations. We "
"will add people to the application and store a list of events in which they "
"participate."
msgstr ""
"我们已经映射了一个持久化实体类到表上。让我们在这个基础上增加一些类之间的关"
"联。首先我们往应用程序里增加人(people)的概念,并存储他们所参与的一个 Event "
"列表。(译者注:与 Event 一样,我们在后面将直接使用 person 来表示“人”而不是它"
"的中文翻译) "

#. Tag: title
#: tutorial.xml:640
#, no-c-format
msgid "Mapping the Person class"
msgstr "映射 Person 类"

#. Tag: para
#: tutorial.xml:642
#, no-c-format
msgid "The first cut of the <literal>Person class looks like this:"
msgstr "最初简单的 <literal>Person 类: "

#. Tag: programlisting
#: tutorial.xml:646
#, fuzzy, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial.domain;\n"
"\n"
"public class Person {\n"
"\n"
"    private Long id;\n"
"    private int age;\n"
"    private String firstname;\n"
"    private String lastname;\n"
"\n"
"    public Person() {}\n"
"\n"
"    // Accessor methods for all properties, private setter for 'id'\n"
"\n"
"}]]>"
msgstr ""
"package events;\n"
"\n"
"public class Person {\n"
"\n"
"    private Long id;\n"
"    private int age;\n"
"    private String firstname;\n"
"    private String lastname;\n"
"\n"
"    public Person() {}\n"
"\n"
"    // Accessor methods for all properties, private setter for 'id'\n"
"\n"
"}"

#. Tag: para
#: tutorial.xml:648
#, no-c-format
msgid ""
"Save this to a file named <filename>src/main/java/org/hibernate/tutorial/"
"domain/Person.java</filename>"
msgstr ""
"把它保存为文件 <filename>src/main/java/org/hibernate/tutorial/domain/Person."
"java</filename>。"

#. Tag: para
#: tutorial.xml:653
#, no-c-format
msgid ""
"Next, create the new mapping file as <filename>src/main/resources/org/"
"hibernate/tutorial/domain/Person.hbm.xml</filename>"
msgstr ""
"然后,创建新的映射文件 <filename>src/main/resources/org/hibernate/tutorial/"
"domain/Person.hbm.xml</filename>。"

#. Tag: programlisting
#: tutorial.xml:658
#, fuzzy, no-c-format
msgid ""
"<![CDATA["
msgstr ""
"<hibernate-mapping>\n"
"\n"
"    <class name=\"events.Person\" table=\"PERSON\">\n"
"        <id name=\"id\" column=\"PERSON_ID\">\n"
"            <generator class=\"native\"/>\n"
"        </id>\n"
"        <property name=\"age\"/>\n"
"        <property name=\"firstname\"/>\n"
"        <property name=\"lastname\"/>\n"
"    </class>\n"
"\n"
"</hibernate-mapping>"

#. Tag: para
#: tutorial.xml:660
#, no-c-format
msgid "Finally, add the new mapping to Hibernate's configuration:"
msgstr "最后,把新的映射加入到 Hibernate 的配置中:"

#. Tag: programlisting
#: tutorial.xml:664
#, fuzzy, no-c-format
msgid ""
"<![CDATA["
msgstr ""
"<mapping resource=\"events/Event.hbm.xml\"/>\n"
"<mapping resource=\"events/Person.hbm.xml\"/>"

#. Tag: para
#: tutorial.xml:666
#, no-c-format
msgid ""
"Create an association between these two entities. Persons can participate in "
"events, and events have participants. The design questions you have to deal "
"with are: directionality, multiplicity, and collection behavior."
msgstr ""
"现在我们在这两个实体之间创建一个关联。显然,persons 可以参与一系列 events,"
"而 events 也有不同的参加者(persons)。我们需要处理的设计问题是关联方向"
"(directionality),阶数(multiplicity)和集合(collection)的行为。 "

#. Tag: title
#: tutorial.xml:676
#, no-c-format
msgid "A unidirectional Set-based association"
msgstr "单向 Set-based 的关??"

#. Tag: para
#: tutorial.xml:678
#, no-c-format
msgid ""
"By adding a collection of events to the <literal>Person class, you "
"can easily navigate to the events for a particular person, without executing "
"an explicit query - by calling <literal>Person#getEvents. Multi-"
"valued associations are represented in Hibernate by one of the Java "
"Collection Framework contracts; here we choose a <interfacename>java.util."
"Set</interfacename> because the collection will not contain duplicate "
"elements and the ordering is not relevant to our examples:"
msgstr ""
"我们将向 <literal>Person 类增加一连串的 events。那样,通过调用 "
"<literal>aPerson.getEvents(),就可以轻松地导航到特定 person 所参与"
"的 events,而不用去执行一个显式的查询。我们使用 Java 的集合类(collection):"
"<literal>Set,因为 set 不包含重复的元素及与我们无关的排序。 "

#. Tag: programlisting
#: tutorial.xml:689
#, fuzzy, no-c-format
msgid ""
"<![CDATA[public class Person {\n"
"\n"
"    private Set events = new HashSet();\n"
"\n"
"    public Set getEvents() {\n"
"        return events;\n"
"    }\n"
"\n"
"    public void setEvents(Set events) {\n"
"        this.events = events;\n"
"    }\n"
"}]]>"
msgstr ""
"public class Person {\n"
"\n"
"    private Set events = new HashSet();\n"
"\n"
"    public Set getEvents() {\n"
"        return events;\n"
"    }\n"
"\n"
"    public void setEvents(Set events) {\n"
"        this.events = events;\n"
"    }\n"
"}"

#. Tag: para
#: tutorial.xml:691
#, no-c-format
msgid ""
"Before mapping this association, let's consider the other side. We could "
"just keep this unidirectional or create another collection on the "
"<literal>Event, if we wanted to be able to navigate it from both "
"directions. This is not necessary, from a functional perspective. You can "
"always execute an explicit query to retrieve the participants for a "
"particular event. This is a design choice left to you, but what is clear "
"from this discussion is the multiplicity of the association: \"many\" valued "
"on both sides is called a <emphasis>many-to-many association. "
"Hence, we use Hibernate's many-to-many mapping:"
msgstr ""
"在映射这个关联之前,先考虑一下此关联的另外一端。很显然,我们可以保持这个关联"
"是单向的。或者,我们可以在 <literal>Event 里创建另外一个集合,如果"
"希望能够双向地导航,如:<literal>anEvent.getParticipants()。从功能"
"的角度来说,这并不是必须的。因为你总可以显式地执行一个查询,以获得某个特定 "
"event 的所有参与者。这是个在设计时需要做出的选择,完全由你来决定,但此讨论中"
"关于关联的阶数是清楚的:即两端都是“多”值的,我们把它叫做<emphasis>多对多"
"(many-to-many)</emphasis>关联。因而,我们使用 Hibernate 的多对多映射: "

#. Tag: programlisting
#: tutorial.xml:704
#, fuzzy, no-c-format
msgid ""
"<![CDATA["
msgstr ""
"<class name=\"events.Person\" table=\"PERSON\">\n"
"    <id name=\"id\" column=\"PERSON_ID\">\n"
"        <generator class=\"native\"/>\n"
"    </id>\n"
"    <property name=\"age\"/>\n"
"    <property name=\"firstname\"/>\n"
"    <property name=\"lastname\"/>\n"
"\n"
"    <set name=\"events\" table=\"PERSON_EVENT\">\n"
"        <key column=\"PERSON_ID\"/>\n"
"        <many-to-many column=\"EVENT_ID\" class=\"events.Event\"/>\n"
"    </set>\n"
"\n"
"</class>"

#. Tag: para
#: tutorial.xml:706
#, no-c-format
msgid ""
"Hibernate supports a broad range of collection mappings, a <literal>setn:"
"m</emphasis> entity relationship, an association table is required. Each row "
"in this table represents a link between a person and an event. The table "
"name is decalred using the <literal>table attribute of the "
"<literal>set element. The identifier column name in the "
"association, for the person side, is defined with the <literal>key "
"element, the column name for the event's side with the <literal>columnmany-to-many. You also have to "
"tell Hibernate the class of the objects in your collection (the class on the "
"other side of the collection of references)."
msgstr ""
"Hibernate 支持各种各样的集合映射,<literal><set> 使用的最为普"
"遍。对于多对多关联(或叫 <emphasis>n:m 实体关系), 需要一个关联表"
"(association table)。<literal>表里面的每一行代表从 person 到 "
"event 的一个关联。表名是由 <literal>set 元素的 table 元素定义,而 event 一端的字段名是由 "
"<literal><many-to-many> 元素的 column 属性"
"定义。你也必须告诉 Hibernate 集合中对象的类(也就是位于这个集合所代表的关联另"
"外一端的类)。 "

#. Tag: para
#: tutorial.xml:722
#, no-c-format
msgid "The database schema for this mapping is therefore:"
msgstr "因而这个映射的数据库 schema 是:"

#. Tag: programlisting
#: tutorial.xml:726
#, fuzzy, no-c-format
msgid ""
"<![CDATA[\n"
"    _____________        __________________\n"
"   |             |      |                  |       _____________\n"
"   |   EVENTS    |      |   PERSON_EVENT   |      |             |\n"
"   |_____________|      |__________________|      |    PERSON   |\n"
"   |             |      |                  |      |_____________|\n"
"   | *EVENT_ID   | <--> | *EVENT_ID        |      |             |\n"
"   |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  |\n"
"   |  TITLE      |      |__________________|      |  AGE        |\n"
"   |_____________|                                |  FIRSTNAME  |\n"
"                                                  |  LASTNAME   |\n"
"                                                  |_____________|\n"
" ]]>"
msgstr ""
"_____________        __________________\n"
"   |             |      |                  |       _____________\n"
"   |   EVENTS    |      |   PERSON_EVENT   |      |             |\n"
"   |_____________|      |__________________|      |    PERSON   |\n"
"   |             |      |                  |      |_____________|\n"
"   | *EVENT_ID   | <--> | *EVENT_ID        |      |             |\n"
"   |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  |\n"
"   |  TITLE      |      |__________________|      |  AGE        |\n"
"   |_____________|                                |  FIRSTNAME  |\n"
"                                                  |  LASTNAME   |\n"
"                                                  |_____________|"

#. Tag: title
#: tutorial.xml:731
#, no-c-format
msgid "Working the association"
msgstr "使关联工作"

#. Tag: para
#: tutorial.xml:733
#, no-c-format
msgid ""
"Now we will bring some people and events together in a new method in "
"<literal>EventManager:"
msgstr ""
"我们把一些 people 和 events 一起放到 <literal>EventManager 的新方法"
"中: "

#. Tag: programlisting
#: tutorial.xml:737
#, fuzzy, no-c-format
msgid ""
"<![CDATA[    private void addPersonToEvent(Long personId, Long eventId) {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"\n"
"        Person aPerson = (Person) session.load(Person.class, personId);\n"
"        Event anEvent = (Event) session.load(Event.class, eventId);\n"
"        aPerson.getEvents().add(anEvent);\n"
"\n"
"        session.getTransaction().commit();\n"
"    }]]>"
msgstr ""
"private void addPersonToEvent(Long personId, Long eventId) {\n"
"\n"
"    Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"    session.beginTransaction();\n"
"\n"
"    Person aPerson = (Person) session.load(Person.class, personId);\n"
"    Event anEvent = (Event) session.load(Event.class, eventId);\n"
"\n"
"    aPerson.getEvents().add(anEvent);\n"
"\n"
"    session.getTransaction().commit();\n"
"}"

#. Tag: para
#: tutorial.xml:739
#, no-c-format
msgid ""
"After loading a <literal>Person and an Event, "
"simply modify the collection using the normal collection methods. There is "
"no explicit call to <literal>update() or save() state, that is, bound to a particular "
"Hibernate <interfacename>org.hibernate.Session, Hibernate "
"monitors any changes and executes SQL in a write-behind fashion. The process "
"of synchronizing the memory state with the database, usually only at the end "
"of a unit of work, is called <emphasis>flushing. In our code, the "
"unit of work ends with a commit, or rollback, of the database transaction."
msgstr ""
"在加载一 <literal>PersonEvent 后,使用普通的"
"集合方法就可容易地修改我们定义的集合。如你所见,没有显式的 <literal>update()"
"</literal> 或 save(),Hibernate 会自动检测到集合已经被修改"
"并需要更新回数据库。这叫做自动脏检查(<emphasis>automatic dirty checking状态,也就是被绑定到某个 Hibernate 的 "
"<literal>Session 上(如:他们刚刚在一个单元操作被加载或者保存),"
"Hibernate 监视任何改变并在后台隐式写的方式执行 SQL。同步内存状态和数据库的过"
"程,通常只在单元操作结束的时候发生,称此过程为清理缓存<emphasis>(flushing)"
"</emphasis>。在我们的代码中,工作单元由数据库事务的提交(或者回滚)来结束——这"
"是由 <literal>CurrentSessionContext 类的 thread "
"配置选项定义的。 "

#. Tag: para
#: tutorial.xml:758
#, no-c-format
msgid ""
"You can load person and event in different units of work. Or you can modify "
"an object outside of a <interfacename>org.hibernate.Session, "
"when it is not in persistent state (if it was persistent before, this state "
"is called <emphasis>detached). You can even modify a collection "
"when it is detached:"
msgstr ""
"当然,你也可以在不同的单元操作里面加载 person 和 event。或在 "
"<literal>Session 以外修改不是处在持久化(persistent)状态下的对象"
"(如果该对象以前曾经被持久化,那么我们称这个状态为<emphasis>脱管(detached)"
"</emphasis>)。你甚至可以在一个集合被脱管时修改它: "

#. Tag: programlisting
#: tutorial.xml:767
#, fuzzy, no-c-format
msgid ""
"<![CDATA[    private void addPersonToEvent(Long personId, Long eventId) {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"\n"
"        Person aPerson = (Person) session\n"
"                .createQuery(\"select p from Person p left join fetch p."
"events where p.id = :pid\")\n"
"                .setParameter(\"pid\", personId)\n"
"                .uniqueResult(); // Eager fetch the collection so we can use "
"it detached\n"
"        Event anEvent = (Event) session.load(Event.class, eventId);\n"
"\n"
"        session.getTransaction().commit();\n"
"\n"
"        // End of first unit of work\n"
"\n"
"        aPerson.getEvents().add(anEvent); // aPerson (and its collection) is "
"detached\n"
"\n"
"        // Begin second unit of work\n"
"\n"
"        Session session2 = HibernateUtil.getSessionFactory()."
"getCurrentSession();\n"
"        session2.beginTransaction();\n"
"        session2.update(aPerson); // Reattachment of aPerson\n"
"\n"
"        session2.getTransaction().commit();\n"
"    }]]>"
msgstr ""
"private void addPersonToEvent(Long personId, Long eventId) {\n"
"\n"
"    Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"    session.beginTransaction();\n"
"\n"
"    Person aPerson = (Person) session\n"
"            .createQuery(\"select p from Person p left join fetch p.events "
"where p.id = :pid\")\n"
"            .setParameter(\"pid\", personId)\n"
"            .uniqueResult(); // Eager fetch the collection so we can use it "
"detached\n"
"\n"
"    Event anEvent = (Event) session.load(Event.class, eventId);\n"
"\n"
"    session.getTransaction().commit();\n"
"\n"
"    // End of first unit of work\n"
"\n"
"    aPerson.getEvents().add(anEvent); // aPerson (and its collection) is "
"detached\n"
"\n"
"    // Begin second unit of work\n"
"\n"
"    Session session2 = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"    session2.beginTransaction();\n"
"\n"
"    session2.update(aPerson); // Reattachment of aPerson\n"
"\n"
"    session2.getTransaction().commit();\n"
"}"

#. Tag: para
#: tutorial.xml:769
#, no-c-format
msgid ""
"The call to <literal>update makes a detached object persistent "
"again by binding it to a new unit of work, so any modifications you made to "
"it while detached can be saved to the database. This includes any "
"modifications (additions/deletions) you made to a collection of that entity "
"object."
msgstr ""
"对 <literal>update 的调用使一个脱管对象重新持久化,你可以说它被绑定"
"到一个新的单元操作上,所以在脱管状态下对它所做的任何修改都会被保存到数据库"
"里。这也包括你对这个实体对象的集合所作的任何改动(增加/删除)。 "

#. Tag: para
#: tutorial.xml:778
#, no-c-format
msgid ""
"This is not much use in our example, but it is an important concept you can "
"incorporate into your own application. Complete this exercise by adding a "
"new action to the main method of the <literal>EventManager and "
"call it from the command line. If you need the identifiers of a person and "
"an event - the <literal>save() method returns it (you might have "
"to modify some of the previous methods to return that identifier):"
msgstr ""
"这对我们当前的情形不是很有用,但它是非常重要的概念,你可以把它融入到你自己的"
"应用程序设计中。在<literal>EventManager的 main 方法中添加一个新的动"
"作,并从命令行运行它来完成我们所做的练习。如果你需要 person 及 event 的标识"
"符 — 那就用 <literal>save() 方法返回它(你可能需要修改前面的一些方"
"法来返回那个标识符): "

#. Tag: programlisting
#: tutorial.xml:786
#, fuzzy, no-c-format
msgid ""
"<![CDATA[        else if (args[0].equals(\"addpersontoevent\")) {\n"
"            Long eventId = mgr.createAndStoreEvent(\"My Event\", new Date"
"());\n"
"            Long personId = mgr.createAndStorePerson(\"Foo\", \"Bar\");\n"
"            mgr.addPersonToEvent(personId, eventId);\n"
"            System.out.println(\"Added person \" + personId + \" to event \" "
"+ eventId);\n"
"        }]]>"
msgstr ""
"else if (args[0].equals(\"addpersontoevent\")) {\n"
"    Long eventId = mgr.createAndStoreEvent(\"My Event\", new Date());\n"
"    Long personId = mgr.createAndStorePerson(\"Foo\", \"Bar\");\n"
"    mgr.addPersonToEvent(personId, eventId);\n"
"    System.out.println(\"Added person \" + personId + \" to event \" + "
"eventId);\n"
"}"

#. Tag: para
#: tutorial.xml:788
#, no-c-format
msgid ""
"This is an example of an association between two equally important classes : "
"two entities. As mentioned earlier, there are other classes and types in a "
"typical model, usually \"less important\". Some you have already seen, like "
"an <literal>int or a java.lang.String. We "
"call these classes <emphasis>value types, and their instances "
"<emphasis>depend on a particular entity. Instances of these types "
"do not have their own identity, nor are they shared between entities. Two "
"persons do not reference the same <literal>firstname object, even "
"if they have the same first name. Value types cannot only be found in the "
"JDK , but you can also write dependent classes yourself such as an "
"<literal>Address or MonetaryAmount class. In "
"fact, in a Hibernate application all JDK classes are considered value types."
msgstr ""
"上面是个关于两个同等重要的实体类间关联的例子。像前面所提到的那样,在特定的模"
"型中也存在其它的类和类型,这些类和类型通常是“次要的”。你已看到过其中的一些,"
"像 <literal>int 或 String。我们称这些类为"
"<emphasis>值类型(value type),它们的实例依赖(depend)"
"</emphasis>在某个特定的实体上。这些类型的实例没有它们自己的标识(identity),"
"也不能在实体间被共享(比如,两个 person 不能引用同一个 <literal>firstname,"
"<literal>MonetaryAmount。 "

#. Tag: para
#: tutorial.xml:806
#, no-c-format
msgid ""
"You can also design a collection of value types. This is conceptually "
"different from a collection of references to other entities, but looks "
"almost the same in Java."
msgstr ""
"你也可以设计一个值类型的集合,这在概念上与引用其它实体的集合有很大的不同,但"
"是在 Java 里面看起来几乎是一样的。 "

#. Tag: title
#: tutorial.xml:815
#, no-c-format
msgid "Collection of values"
msgstr "值类型的集合"

#. Tag: para
#: tutorial.xml:817
#, no-c-format
msgid ""
"Let's add a collection of email addresses to the <literal>Person "
"entity. This will be represented as a <interfacename>java.util.Setjava.lang.String instances:"
msgstr ""
"让我们在 <literal>Person 实体里添加一个电子邮件的集合。这将以 "
"<classname>java.lang.String 实例的 java.util.Set is as follows:"
msgstr "这个 <literal>Set 的映射如下:"

#. Tag: programlisting
#: tutorial.xml:829
#, fuzzy, no-c-format
msgid ""
"<![CDATA[        "
msgstr ""
"<set name=\"emailAddresses\" table=\"PERSON_EMAIL_ADDR\">\n"
"    <key column=\"PERSON_ID\"/>\n"
"    <element type=\"string\" column=\"EMAIL_ADDR\"/>\n"
"</set>"

#. Tag: para
#: tutorial.xml:831
#, no-c-format
msgid ""
"The difference compared with the earlier mapping is the use of the "
"<literal>element part which tells Hibernate that the collection "
"does not contain references to another entity, but is rather a collection "
"whose elements are values types, here specifically of type <literal>string attribute of the set element defines the foreign-key column name in the "
"collection table. The <literal>column attribute in the "
"<literal>element element defines the column name where the email "
"address values will actually be stored."
msgstr ""
"比较这次和此前映射的差别,主要在于 <literal>element 部分,这次并没"
"有包含对其它实体引用的集合,而是元素类型为 <literal>String 的集合"
"(在映射中使用小写的名字”string“是向你表明它是一个 Hibernate 的映射类型或者类"
"型转换器)。和之前一样,<literal>set 元素的 tablekey 元素定义了在集合表"
"中外键的字段名。<literal>element 元素的 column "
"属性定义用于实际保存 <literal>String 值的字段名。 "

#. Tag: para
#: tutorial.xml:847
#, no-c-format
msgid "Here is the updated schema:"
msgstr "看一下修改后的数据库 schema。 "

#. Tag: programlisting
#: tutorial.xml:851
#, fuzzy, no-c-format
msgid ""
"<![CDATA[\n"
"  _____________        __________________\n"
" |             |      |                  |       _____________\n"
" |   EVENTS    |      |   PERSON_EVENT   |      |             |       "
"___________________\n"
" |_____________|      |__________________|      |    PERSON   |      "
"|                   |\n"
" |             |      |                  |      |_____________|      | "
"PERSON_EMAIL_ADDR |\n"
" | *EVENT_ID   | <--> | *EVENT_ID        |      |             |      |"
"___________________|\n"
" |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  | <--> |  "
"*PERSON_ID       |\n"
" |  TITLE      |      |__________________|      |  AGE        |      |  "
"*EMAIL_ADDR      |\n"
" |_____________|                                |  FIRSTNAME  |      |"
"___________________|\n"
"                                                |  LASTNAME   |\n"
"                                                |_____________|\n"
" ]]>"
msgstr ""
"_____________        __________________\n"
" |             |      |                  |       _____________\n"
" |   EVENTS    |      |   PERSON_EVENT   |      |             |       "
"___________________\n"
" |_____________|      |__________________|      |    PERSON   |      "
"|                   |\n"
" |             |      |                  |      |_____________|      | "
"PERSON_EMAIL_ADDR |\n"
" | *EVENT_ID   | <--> | *EVENT_ID        |      |             |      |"
"___________________|\n"
" |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  | <--"
"> |  *PERSON_ID       |\n"
" |  TITLE      |      |__________________|      |  AGE        |      |  "
"*EMAIL_ADDR      |\n"
" |_____________|                                |  FIRSTNAME  |      |"
"___________________|\n"
"                                                |  LASTNAME   |\n"
"                                                |_____________|"

#. Tag: para
#: tutorial.xml:853
#, no-c-format
msgid ""
"You can see that the primary key of the collection table is in fact a "
"composite key that uses both columns. This also implies that there cannot be "
"duplicate email addresses per person, which is exactly the semantics we need "
"for a set in Java."
msgstr ""
"你可以看到集合表的主键实际上是个复合主键,同时使用了两个字段。这也暗示了对于"
"同一个 person 不能有重复的 email 地址,这正是 Java 里面使用 Set 时候所需要的"
"语义(Set 里元素不能重复)。"

#. Tag: para
#: tutorial.xml:859
#, no-c-format
msgid ""
"You can now try to add elements to this collection, just like we did before "
"by linking persons and events. It is the same code in Java:"
msgstr ""
"你现在可以试着把元素加入到这个集合,就像我们在之前关联 person 和 event 的那"
"样。其实现的 Java 代码是相同的: "

#. Tag: programlisting
#: tutorial.xml:864
#, fuzzy, no-c-format
msgid ""
"<![CDATA[    private void addEmailToPerson(Long personId, String "
"emailAddress) {\n"
"        Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"        session.beginTransaction();\n"
"\n"
"        Person aPerson = (Person) session.load(Person.class, personId);\n"
"        // adding to the emailAddress collection might trigger a lazy load "
"of the collection\n"
"        aPerson.getEmailAddresses().add(emailAddress);\n"
"\n"
"        session.getTransaction().commit();\n"
"    }]]>"
msgstr ""
"private void addEmailToPerson(Long personId, String emailAddress) {\n"
"\n"
"    Session session = HibernateUtil.getSessionFactory().getCurrentSession"
"();\n"
"    session.beginTransaction();\n"
"\n"
"    Person aPerson = (Person) session.load(Person.class, personId);\n"
"\n"
"    // The getEmailAddresses() might trigger a lazy load of the collection\n"
"    aPerson.getEmailAddresses().add(emailAddress);\n"
"\n"
"    session.getTransaction().commit();\n"
"}"

#. Tag: para
#: tutorial.xml:866
#, no-c-format
msgid ""
"This time we did not use a <emphasis>fetch query to initialize "
"the collection. Monitor the SQL log and try to optimize this with an eager "
"fetch."
msgstr ""
"这次我们没有使用 <emphasis>fetch 查询来初始化集合。因此,调用其 "
"getter 方法会触发另一附加的 select 来初始化集合,这样我们才能把元素添加进去。"
"检查 SQL log,试着通过预先抓取来优化它。 "

#. Tag: title
#: tutorial.xml:875
#, no-c-format
msgid "Bi-directional associations"
msgstr "双向关联"

#. Tag: para
#: tutorial.xml:877
#, no-c-format
msgid ""
"Next you will map a bi-directional association. You will make the "
"association between person and event work from both sides in Java. The "
"database schema does not change, so you will still have many-to-many "
"multiplicity."
msgstr ""
"接下来我们将映射双向关联(bi-directional association)— 在 Java 里让 person "
"和 event 可以从关联的任何一端访问另一端。当然,数据库 schema 没有改变,我们仍"
"然需要多对多的阶数。一个关系型数据库要比网络编程语言更加灵活,所以它并不需要"
"任何像导航方向(navigation direction)的东西 — 数据可以用任何可能的方式进行查"
"看和获取。 "

#. Tag: para
#: tutorial.xml:885
#, no-c-format
msgid ""
"A relational database is more flexible than a network programming language, "
"in that it does not need a navigation direction; data can be viewed and "
"retrieved in any possible way."
msgstr ""
"关系型数据库比网络编程语言更为灵活,因为它不需要方向导航,其数据可以用任何可"
"能的方式进行查看和提取。"

#. Tag: para
#: tutorial.xml:893
#, no-c-format
msgid ""
"First, add a collection of participants to the <literal>Event "
"class:"
msgstr ""
"首先,把一个参与者(person)的集合加入 <literal>Event 类中: "

#. Tag: programlisting
#: tutorial.xml:898
#, fuzzy, no-c-format
msgid ""
"<![CDATA[    private Set participants = new HashSet();\n"
"\n"
"    public Set getParticipants() {\n"
"        return participants;\n"
"    }\n"
"\n"
"    public void setParticipants(Set participants) {\n"
"        this.participants = participants;\n"
"    }]]>"
msgstr ""
"private Set participants = new HashSet();\n"
"\n"
"public Set getParticipants() {\n"
"    return participants;\n"
"}\n"
"\n"
"public void setParticipants(Set participants) {\n"
"    this.participants = participants;\n"
"}"

#. Tag: para
#: tutorial.xml:900
#, no-c-format
msgid ""
"Now map this side of the association in <literal>Event.hbm.xml."
msgstr "在 <literal>Event.hbm.xml 里面也映射这个关联。 "

#. Tag: programlisting
#: tutorial.xml:904
#, fuzzy, no-c-format
msgid ""
"<![CDATA[        "
msgstr ""
"<set name=\"participants\" table=\"PERSON_EVENT\" inverse=\"true\">\n"
"    <key column=\"EVENT_ID\"/>\n"
"    <many-to-many column=\"PERSON_ID\" class=\"events.Person\"/>\n"
"</set>"

#. Tag: para
#: tutorial.xml:906
#, no-c-format
msgid ""
"These are normal <literal>set mappings in both mapping documents. "
"Notice that the column names in <literal>key and many-to-"
"many</literal> swap in both mapping documents. The most important addition "
"here is the <literal>inverse=\"true\" attribute in the "
"<literal>set element of the Event's collection "
"mapping."
msgstr ""
"如你所见,两个映射文件里都有普通的 <literal>set 映射。注意在两个映"
"射文件中,互换了 <literal>key 和 many-to-many 的"
"字段名。这里最重要的是 <literal>Event 映射文件里增加了 "
"<literal>set 元素的 inverse=\"true\" 属性。 "

#. Tag: para
#: tutorial.xml:914
#, no-c-format
msgid ""
"What this means is that Hibernate should take the other side, the "
"<literal>Person class, when it needs to find out information about "
"the link between the two. This will be a lot easier to understand once you "
"see how the bi-directional link between our two entities is created."
msgstr ""
"这意味着在需要的时候,Hibernate 能在关联的另一端 — <literal>Person "
"类得到两个实体间关联的信息。这将会极大地帮助你理解双向关联是如何在两个实体间"
"被创建的。 "

#. Tag: title
#: tutorial.xml:923
#, no-c-format
msgid "Working bi-directional links"
msgstr "使双向连起来"

#. Tag: para
#: tutorial.xml:925
#, no-c-format
msgid ""
"First, keep in mind that Hibernate does not affect normal Java semantics. "
"How did we create a link between a <literal>Person and an "
"<literal>Event in the unidirectional example? You add an instance "
"of <literal>Event to the collection of event references, of an "
"instance of <literal>Person. If you want to make this link bi-"
"directional, you have to do the same on the other side by adding a "
"<literal>Person reference to the collection in an EventEvent 之间创建联系的?我"
"们把 <literal>Event 实例添加到 Person 实例内的 "
"event 引用集合里。因此很显然,如果我们要让这个关联可以双向地工作,我们需要在"
"另外一端做同样的事情 - 把 <literal>Person 实例加入 "
"<literal>Event 类内的 Person 引用集合。这“在关联的两端设置联系”是完"
"全必要的而且你都得这么做。 "

#. Tag: para
#: tutorial.xml:935
#, no-c-format
msgid ""
"Many developers program defensively and create link management methods to "
"correctly set both sides (for example, in <literal>Person):"
msgstr ""
"许多开发人员防御式地编程,创建管理关联的方法来保证正确的设置了关联的两端,比"
"如在 <literal>Person 里: "

#. Tag: programlisting
#: tutorial.xml:940
#, fuzzy, no-c-format
msgid ""
"<![CDATA[    protected Set getEvents() {\n"
"        return events;\n"
"    }\n"
"\n"
"    protected void setEvents(Set events) {\n"
"        this.events = events;\n"
"    }\n"
"\n"
"    public void addToEvent(Event event) {\n"
"        this.getEvents().add(event);\n"
"        event.getParticipants().add(this);\n"
"    }\n"
"\n"
"    public void removeFromEvent(Event event) {\n"
"        this.getEvents().remove(event);\n"
"        event.getParticipants().remove(this);\n"
"    }]]>"
msgstr ""
"protected Set getEvents() {\n"
"    return events;\n"
"}\n"
"\n"
"protected void setEvents(Set events) {\n"
"    this.events = events;\n"
"}\n"
"\n"
"public void addToEvent(Event event) {\n"
"    this.getEvents().add(event);\n"
"    event.getParticipants().add(this);\n"
"}\n"
"\n"
"public void removeFromEvent(Event event) {\n"
"    this.getEvents().remove(event);\n"
"    event.getParticipants().remove(this);\n"
"}"

#. Tag: para
#: tutorial.xml:942
#, no-c-format
msgid ""
"The get and set methods for the collection are now protected. This allows "
"classes in the same package and subclasses to still access the methods, but "
"prevents everybody else from altering the collections directly. Repeat the "
"steps for the collection on the other side."
msgstr ""
"注意现在对于集合的 get 和 set 方法的访问级别是 protected — 这允许在位于同一个"
"包(package)中的类以及继承自这个类的子类可以访问这些方法,但禁止其他任何人的"
"直接访问,避免了集合内容的混乱。你应尽可能地在另一端也把集合的访问级别设成 "
"protected。 "

#. Tag: para
#: tutorial.xml:949
#, no-c-format
msgid ""
"What about the <literal>inverse mapping attribute? For you, and "
"for Java, a bi-directional link is simply a matter of setting the references "
"on both sides correctly. Hibernate, however, does not have enough "
"information to correctly arrange SQL <literal>INSERT and "
"<literal>UPDATE statements (to avoid constraint violations). "
"Making one side of the association <literal>inverse tells "
"Hibernate to consider it a <emphasis>mirror of the other side. "
"That is all that is necessary for Hibernate to resolve any issues that arise "
"when transforming a directional navigation model to a SQL database schema. "
"The rules are straightforward: all bi-directional associations need one side "
"as <literal>inverse. In a one-to-many association it has to be the "
"many-side, and in many-to-many association you can select either side."
msgstr ""
"<literal>inverse 映射属性究竟表示什么呢?对于你和 Java 来说,一个双"
"向关联仅仅是在两端简单地正确设置引用。然而,Hibernate 并没有足够的信息去正确"
"地执行 <literal>INSERT 和 UPDATE 语句(以避免违"
"反数据库约束),所以它需要一些帮助来正确的处理双向关联。把关联的一端设置为 "
"<literal>inverse 将告诉 Hibernate 忽略关联的这一端,把这端看成是另"
"外一端的一个<emphasis>镜象(mirror)。这就是所需的全部信息,"
"Hibernate 利用这些信息来处理把一个有向导航模型转移到数据库 schema 时的所有问"
"题。你只需要记住这个直观的规则:所有的双向关联需要有一端被设置为 "
"<literal>inverse。在一对多关联中它必须是代表多(many)的那端。而在"
"多对多(many-to-many)关联中,你可以任意选取一端,因为两端之间并没有差别。 "

#. Tag: title
#: tutorial.xml:965
#, no-c-format
msgid "Part 3 - The EventManager web application"
msgstr "第三部分 - EventManager web 应用程序"

#. Tag: para
#: tutorial.xml:967
#, no-c-format
msgid ""
"A Hibernate web application uses <literal>Session and "
"<literal>Transaction almost like a standalone application. "
"However, some common patterns are useful. You can now write an "
"<literal>EventManagerServlet. This servlet can list all events "
"stored in the database, and it provides an HTML form to enter new events."
msgstr ""
"Hibernate web 应用程序使用 <literal>Session 和 "
"<literal>Transaction 的方式几乎和独立应用程序是一样的。但是,有一些"
"常见的模式(pattern)非常有用。现在我们编写一个 "
"<literal>EventManagerServlet。这个 servlet 可以列出数据库中保存的所"
"有的 events,还提供一个 HTML 表单来增加新的 events。 "

#. Tag: title
#: tutorial.xml:975
#, no-c-format
msgid "Writing the basic servlet"
msgstr "编写基本的 servlet"

#. Tag: para
#: tutorial.xml:977
#, no-c-format
msgid ""
"First we need create our basic processing servlet. Since our servlet only "
"handles HTTP <literal>GET requests, we will only implement the "
"<literal>doGet() method:"
msgstr ""
"这个 servlet 只处理 HTTP <literal>GET 请求,因此,我们要实现的是 "
"<literal>doGet() 方法: "

#. Tag: programlisting
#: tutorial.xml:983
#, fuzzy, no-c-format
msgid ""
"<![CDATA[package org.hibernate.tutorial.web;\n"
"\n"
"// Imports\n"
"\n"
"public class EventManagerServlet extends HttpServlet {\n"
"\n"
"    protected void doGet(\n"
"            HttpServletRequest request,\n"
"            HttpServletResponse response) throws ServletException, "
"IOException {\n"
"\n"
"        SimpleDateFormat dateFormatter = new SimpleDateFormat( \"dd.MM.yyyy"
"\" );\n"
"\n"
"        try {\n"
"            // Begin unit of work\n"
"            HibernateUtil.getSessionFactory().getCurrentSession()."
"beginTransaction();\n"
"\n"
"            // Process request and render page...\n"
"\n"
"            // End unit of work\n"
"            HibernateUtil.getSessionFactory().getCurrentSession()."
"getTransaction().commit();\n"
"        }\n"
"        catch (Exception ex) {\n"
"            HibernateUtil.getSessionFactory().getCurrentSession()."
"getTransaction().rollback();\n"
"            if ( ServletException.class.isInstance( ex ) ) {\n"
"                throw ( ServletException ) ex;\n"
"            }\n"
"            else {\n"
"                throw new ServletException( ex );\n"
"            }\n"
"        }\n"
"    }\n"
"\n"
"}]]>"
msgstr ""
"protected void doGet(HttpServletRequest request,\n"
"                     HttpServletResponse response)\n"
"        throws ServletException, IOException {\n"
"\n"
"    SimpleDateFormat dateFormatter = new SimpleDateFormat(\"dd.MM.yyyy\");\n"
"\n"
"    try {\n"
"        // Begin unit of work\n"
"        HibernateUtil.getSessionFactory()\n"
"                .getCurrentSession().beginTransaction();\n"
"\n"
"        // Process request and render page...\n"
"\n"
"        // End unit of work\n"
"        HibernateUtil.getSessionFactory()\n"
"                .getCurrentSession().getTransaction().commit();\n"
"\n"
"    } catch (Exception ex) {\n"
"        HibernateUtil.getSessionFactory()\n"
"                .getCurrentSession().getTransaction().rollback();\n"
"        throw new ServletException(ex);\n"
"    }\n"
"\n"
"}"

#. Tag: para
#: tutorial.xml:985
#, no-c-format
msgid ""
"Save this servlet as <filename>src/main/java/org/hibernate/tutorial/web/"
"EventManagerServlet.java</filename>"
msgstr ""
"把这个 servlet 保存为 <filename>src/main/java/org/hibernate/tutorial/web/"
"EventManagerServlet.java</filename>。"

#. Tag: para
#: tutorial.xml:990
#, no-c-format
msgid ""
"The pattern applied here is called <emphasis>session-per-request. "
"When a request hits the servlet, a new Hibernate <literal>Session "
"is opened through the first call to <literal>getCurrentSession() "
"on the <literal>SessionFactory. A database transaction is then "
"started. All data access occurs inside a transaction irrespective of whether "
"the data is read or written. Do not use the auto-commit mode in applications."
msgstr ""
"我们称这里应用的模式为每次请求一个 session<emphasis>(session-per-request)SessionFactorySession。然"
"后启动一个数据库事务 — 所有的数据访问都是在事务中进行,不管是读还是写(我们在"
"应用程序中不使用 auto-commit 模式)。 "

#. Tag: para
#: tutorial.xml:999
#, no-c-format
msgid ""
"Do <emphasis>not use a new Hibernate Session "
"for every database operation. Use one Hibernate <literal>Session "
"that is scoped to the whole request. Use <literal>getCurrentSession()为每次数据库操作都使用一个新的 Hibernate "
"<literal>Session。将 Hibernate Session 的范围设"
"置为整个请求。要用 <literal>getCurrentSession(),这样它自动会绑定到"
"当前 Java 线程。"

#. Tag: para
#: tutorial.xml:1006
#, no-c-format
msgid ""
"Next, the possible actions of the request are processed and the response "
"HTML is rendered. We will get to that part soon."
msgstr ""
"下一步,对请求的可能动作进行处理,渲染出反馈的 HTML。我们很快就会涉及到那部"
"分。 "

#. Tag: para
#: tutorial.xml:1011
#, no-c-format
msgid ""
"Finally, the unit of work ends when processing and rendering are complete. "
"If any problems occurred during processing or rendering, an exception will "
"be thrown and the database transaction rolled back. This completes the "
"<literal>session-per-request pattern. Instead of the transaction "
"demarcation code in every servlet, you could also write a servlet filter. "
"See the Hibernate website and Wiki for more information about this pattern "
"called <emphasis>Open Session in View. You will need it as soon "
"as you consider rendering your view in JSP, not in a servlet."
msgstr ""
"最后,当处理与渲染都结束的时候,这个工作单元就结束了。假若在处理或渲染的时候"
"有任何错误发生,会抛出一个异常,回滚数据库事务。这样,<literal>session-per-"
"request</literal> 模式就完成了。为了避免在每个 servlet 中都编写事务边界界定的"
"代码,可以考虑写一个 servlet 过滤器(filter)来更好地解决。关于这一模式的更多"
"信息,请参阅 Hibernate 网站和 Wiki,这一模式叫做 <emphasis>Open Session in "
"View</emphasis> — 只要你考虑用JSP来渲染你的视图(view),而不是在servlet中,"
"你就会很快用到它。 "

#. Tag: title
#: tutorial.xml:1025
#, no-c-format
msgid "Processing and rendering"
msgstr "处理与渲染"

#. Tag: para
#: tutorial.xml:1027
#, no-c-format
msgid ""
"Now you can implement the processing of the request and the rendering of the "
"page."
msgstr "我们来实现处理请求以及渲染页面的工作。 "

#. Tag: programlisting
#: tutorial.xml:1031
#, fuzzy, no-c-format
msgid ""
"<![CDATA[        // Write HTML header\n"
"        PrintWriter out = response.getWriter();\n"
"        out.println(\"<html>Event Manager"
"\");\n"
"\n"
"        // Handle actions\n"
"        if ( \"store\".equals(request.getParameter(\"action\")) ) {\n"
"\n"
"            String eventTitle = request.getParameter(\"eventTitle\");\n"
"            String eventDate = request.getParameter(\"eventDate\");\n"
"\n"
"            if ( \"\".equals(eventTitle) || \"\".equals(eventDate) ) {\n"
"                out.println(\"<b>Please enter event title and date.Added event.\");\n"
"            }\n"
"        }\n"
"\n"
"        // Print page\n"
"       printEventForm(out);\n"
"       listEvents(out, dateFormatter);\n"
"\n"
"       // Write HTML footer\n"
"       out.println(\"</body>\");\n"
"       out.flush();\n"
"       out.close();]]>"
msgstr ""
"// Write HTML header\n"
"PrintWriter out = response.getWriter();\n"
"out.println(\"<html><head><title>Event Manager</"
"title></head><body>\");\n"
"\n"
"// Handle actions\n"
"if ( \"store\".equals(request.getParameter(\"action\")) ) {\n"
"\n"
"    String eventTitle = request.getParameter(\"eventTitle\");\n"
"    String eventDate = request.getParameter(\"eventDate\");\n"
"\n"
"    if ( \"\".equals(eventTitle) || \"\".equals(eventDate) ) {\n"
"        out.println(\"<b><i>Please enter event title and date."
"</i></b>\");\n"
"    } else {\n"
"        createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));\n"
"        out.println(\"<b><i>Added event.</i></b>"
"\");\n"
"    }\n"
"}\n"
"\n"
"// Print page\n"
"printEventForm(out);\n"
"listEvents(out, dateFormatter);\n"
"\n"
"// Write HTML footer\n"
"out.println(\"</body></html>\");\n"
"out.flush();\n"
"out.close();"

#. Tag: para
#: tutorial.xml:1033
#, no-c-format
msgid ""
"This coding style, with a mix of Java and HTML, would not scale in a more "
"complex application—keep in mind that we are only illustrating basic "
"Hibernate concepts in this tutorial. The code prints an HTML header and a "
"footer. Inside this page, an HTML form for event entry and a list of all "
"events in the database are printed. The first method is trivial and only "
"outputs HTML:"
msgstr ""
"必须承认,这种编码风格把 Java 和 HTML 混在一起,在更复杂的应用程序里不应该大"
"量使用 — 记住,在本章里我们仅仅是展示了 Hibernate 的基本概念。这段代码打印出"
"了 HTML 页眉和页脚,在这个页面里,还打印了一个输入 events 条目的表单单并列出"
"了数据库里的有的 events。第一个方法微不足道,仅仅是输出 HTML:"

#. Tag: programlisting
#: tutorial.xml:1042
#, fuzzy, no-c-format
msgid ""
"<![CDATA[    private void printEventForm(PrintWriter out) {\n"
"        out.println(\"<h2>Add new event:\");\n"
"        out.println(\"<form>\");\n"
"        out.println(\"Title: <input name='eventTitle' length='50'/>
" "\");\n" " out.println(\"Date (e.g. 24.12.2009): <input name='eventDate' " "length='10'/><br/>\");\n" " out.println(\"<input type='submit' name='action' value='store'/>" "\");\n" " out.println(\"</form>\");\n" " }]]>" msgstr "" "private void printEventForm(PrintWriter out) {\n" " out.println(\"<h2>Add new event:</h2>\");\n" " out.println(\"<form>\");\n" " out.println(\"Title: <input name='eventTitle' length='50'/><br/" ">\");\n" " out.println(\"Date (e.g. 24.12.2009): <input name='eventDate' " "length='10'/><br/>\");\n" " out.println(\"<input type='submit' name='action' value='store'/>" "\");\n" " out.println(\"</form>\");\n" "}" #. Tag: para #: tutorial.xml:1044 #, no-c-format msgid "" "The <literal>listEvents() method uses the Hibernate " "<literal>Session bound to the current thread to execute a query:" msgstr "" "<literal>listEvents() 方法使用绑定到当前线程的 Hibernate " "<literal>Session 来执行查询:" #. Tag: programlisting #: tutorial.xml:1050 #, fuzzy, no-c-format msgid "" "<![CDATA[ private void listEvents(PrintWriter out, SimpleDateFormat " "dateFormatter) {\n" "\n" " List result = HibernateUtil.getSessionFactory()\n" " .getCurrentSession().createCriteria(Event.class).list();\n" " if (result.size() > 0) {\n" " out.println(\"<h2>Events in database:\");\n" " out.println(\"<table border='1'>\");\n" " out.println(\"<tr>\");\n" " out.println(\"<th>Event title\");\n" " out.println(\"<th>Event date\");\n" " out.println(\"</tr>\");\n" " Iterator it = result.iterator();\n" " while (it.hasNext()) {\n" " Event event = (Event) it.next();\n" " out.println(\"<tr>\");\n" " out.println(\"<td>\" + event.getTitle() + \"
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.