alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  
\");\n" " out.println(\"<td>\" + dateFormatter.format(event.getDate()) + \"\");\n" " out.println(\"</tr>\");\n" " }\n" " out.println(\"</table>\");\n" " }\n" " }]]>" msgstr "" #. Tag: para #: tutorial.xml:1052 #, no-c-format msgid "Finally, the <literal>store action is dispatched to the createAndStoreEvent() method, which also uses the Session of the current thread:" msgstr "" #. Tag: programlisting #: tutorial.xml:1058 #, 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 "" #. 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 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 "" #. Tag: title #: tutorial.xml:1074 #, no-c-format msgid "Deploying and testing" msgstr "" #. Tag: para #: tutorial.xml:1076 #, no-c-format msgid "To deploy this application for testing we must create a Web ARchive (WAR). First we must define the WAR descriptor as <filename>src/main/webapp/WEB-INF/web.xml" msgstr "" #. Tag: programlisting #: tutorial.xml:1082 #, no-c-format msgid "" "<![CDATA[\n" " <servlet-class>org.hibernate.tutorial.web.EventManagerServlet\n" " </servlet>\n" "\n" " <servlet-mapping>\n" " <servlet-name>Event Manager\n" " <url-pattern>/eventmanager\n" " </servlet-mapping>\n" "</web-app>]]>" msgstr "" #. Tag: para #: tutorial.xml:1084 #, no-c-format msgid "To build and deploy call <literal>mvn package in your project directory and copy the hibernate-tutorial.war file into your Tomcat webapps directory." msgstr "" #. Tag: para #: tutorial.xml:1091 #, no-c-format msgid "If you do not have Tomcat installed, download it from <ulink url=\"http://tomcat.apache.org/\"> and follow the installation instructions. Our application requires no changes to the standard Tomcat configuration." msgstr "" #. 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 HibernateUtil is called) and to get the detailed output if any exceptions occurs." msgstr "" #. 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 ""

Other Hibernate examples (source code examples)

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

Hibernate example source code file (tutorial.pot)

This example Hibernate source code file (tutorial.pot) 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, info, java, person, tag, tag, the, the, this, you

The Hibernate tutorial.pot source code

# SOME DESCRIPTIVE TITLE.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: http://bugs.kde.org\n"
"POT-Creation-Date: 2010-07-20 21:02+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <kde-i18n-doc@kde.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: application/x-xml2pot; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\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 ""

#. 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 ""

#. Tag: para
#: tutorial.xml:54
#, no-c-format
msgid "The distribution contains another example application under the <filename>tutorial/eg project source directory."
msgstr ""

#. Tag: title
#: tutorial.xml:62
#, no-c-format
msgid "Part 1 - The first Hibernate Application"
msgstr ""

#. 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 ""

#. 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 ""

#. 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 layout. As this tutorial is to be a web application, we will be creating and making use of src/main/java, src/main/resources and src/main/webapp directories."
msgstr ""

#. 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 ""

#. 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 ""

#. Tag: para
#: tutorial.xml:100
#, 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 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."
msgstr ""

#. Tag: para
#: tutorial.xml:117
#, no-c-format
msgid "Save this file as <filename>pom.xml in the project root directory."
msgstr ""

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

#. 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 ""

#. 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 ""

#. 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 ""

#. 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 ""

#. 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 ""

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

#. Tag: title
#: tutorial.xml:171
#, no-c-format
msgid "The mapping file"
msgstr ""

#. Tag: para
#: tutorial.xml:173
#, no-c-format
msgid "Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use."
msgstr ""

#. Tag: para
#: tutorial.xml:181
#, no-c-format
msgid "The basic structure of a mapping file looks like this:"
msgstr ""

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

#. 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 hibernate3.jar, if using the distribution bundle)."
msgstr ""

#. 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 ""

#. Tag: para
#: tutorial.xml:206
#, no-c-format
msgid "Between the two <literal>hibernate-mapping tags, include a 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 ""

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

#. 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 ""

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

#. Tag: para
#: tutorial.xml:227
#, no-c-format
msgid "The <literal>id element is the declaration of the identifier property. The name=\"id\" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the EVENTS table holds the primary key value."
msgstr ""

#. 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 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 ""

#. Tag: para
#: tutorial.xml:249
#, no-c-format
msgid "<literal>native is no longer consider the best strategy in terms of portability. for further discussion, see"
msgstr ""

#. 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 ""

#. Tag: para
#: tutorial.xml:263
#, no-c-format
msgid "Similar to the <literal>id element, the name attribute of the property element tells Hibernate which getter and setter methods to use. In this case, Hibernate will search for getDate(), setDate(), getTitle() and setTitle() methods."
msgstr ""

#. Tag: para
#: tutorial.xml:274
#, no-c-format
msgid "Why does the <literal>date property mapping include the column attribute, but the title does not? Without the column attribute, Hibernate by default uses the property name as the column name. This works for title, however, date is a reserved keyword in most databases so you will need to map it to a different name."
msgstr ""

#. 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 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 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 date property. Hibernate cannot know if the property, which is of java.util.Date, should map to a SQL date, timestamp, or time column. Full date and time information is preserved by mapping the property with a timestamp converter."
msgstr ""

#. Tag: para
#: tutorial.xml:300
#, no-c-format
msgid "Hibernate makes this mapping type determination using reflection when the mapping files are processed. This can take time and resources, so if startup performance is important you should consider explicitly defining the type to use."
msgstr ""

#. Tag: para
#: tutorial.xml:307
#, no-c-format
msgid "Save this mapping file as <filename>src/main/resources/org/hibernate/tutorial/domain/Event.hbm.xml."
msgstr ""

#. Tag: title
#: tutorial.xml:315
#, no-c-format
msgid "Hibernate configuration"
msgstr ""

#. Tag: para
#: tutorial.xml:317
#, no-c-format
msgid "At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate. First let's set up HSQLDB to run in \"server mode\""
msgstr ""

#. Tag: para
#: tutorial.xml:324
#, no-c-format
msgid "We do this do that the data remains between runs."
msgstr ""

#. Tag: para
#: tutorial.xml:329
#, no-c-format
msgid "We will utilize the Maven exec plugin to launch the HSQLDB server by running: <command> mvn exec:java -Dexec.mainClass=\"org.hsqldb.Server\" -Dexec.args=\"-database.0 file:target/data/tutorial\" You will see it start up and bind to a TCP/IP socket; this is where our application will connect later. If you want to start with a fresh database during this tutorial, shutdown HSQLDB, delete all files in the target/data directory, and start HSQLDB again."
msgstr ""

#. 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). Hibernate comes with support for two third-party open source JDBC connection pools: c3p0 and proxool. However, we will be using the Hibernate built-in connection pool for this tutorial."
msgstr ""

#. 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 ""

#. Tag: para
#: tutorial.xml:357
#, no-c-format
msgid "For Hibernate's configuration, we can use a simple <literal>hibernate.properties file, a more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:363
#, no-c-format
msgid ""
      "<![CDATA[\n"
      "        <property name=\"connection.url\">jdbc:hsqldb:hsql://localhost\n"
      "        <property name=\"connection.username\">sa\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"
      "        <!-- Enable Hibernate's automatic session context management -->\n"
      "        <property name=\"current_session_context_class\">thread\n"
      "\n"
      "        <!-- Disable the second-level cache  -->\n"
      "        <property name=\"cache.provider_class\">org.hibernate.cache.NoCacheProvider\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 ""

#. Tag: para
#: tutorial.xml:366
#, no-c-format
msgid "Notice that this configuration file specifies a different DTD"
msgstr ""

#. 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 <session-factory> configurations in several configuration files."
msgstr ""

#. 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 property element specifies the particular SQL variant Hibernate generates."
msgstr ""

#. Tag: para
#: tutorial.xml:383
#, 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 ""

#. 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 SchemaExport Ant task. Finally, add the mapping file(s) for persistent classes to the configuration."
msgstr ""

#. Tag: para
#: tutorial.xml:398
#, no-c-format
msgid "Save this file as <filename>hibernate.cfg.xml into the src/main/resources directory."
msgstr ""

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

#. 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. Maven will read the /pom.xml file we created earlier and know how to perform some basic project tasks. First, lets run the compile goal to make sure we can compile everything so far:"
msgstr ""

#. 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 org.hibernate.SessionFactory object and storing it somewhere for easy access in application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once."
msgstr ""

#. 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 org.hibernate.SessionFactory more convenient."
msgstr ""

#. Tag: programlisting
#: tutorial.xml:445
#, no-c-format
msgid ""
      "<![CDATA[package org.hibernate.tutorial.util;\n"
      "\n"
      "import org.hibernate.SessionFactory;\n"
      "import org.hibernate.cfg.Configuration;\n"
      "\n"
      "public class HibernateUtil {\n"
      "\n"
      "    private static final SessionFactory sessionFactory = buildSessionFactory();\n"
      "\n"
      "    private static SessionFactory buildSessionFactory() {\n"
      "        try {\n"
      "            // Create the SessionFactory from hibernate.cfg.xml\n"
      "            return new Configuration().configure().buildSessionFactory();\n"
      "        }\n"
      "        catch (Throwable ex) {\n"
      "            // Make sure you log the exception, as it might be swallowed\n"
      "            System.err.println(\"Initial SessionFactory creation failed.\" + ex);\n"
      "            throw new ExceptionInInitializerError(ex);\n"
      "        }\n"
      "    }\n"
      "\n"
      "    public static SessionFactory getSessionFactory() {\n"
      "        return sessionFactory;\n"
      "    }\n"
      "\n"
      "}]]>"
msgstr ""

#. Tag: para
#: tutorial.xml:447
#, no-c-format
msgid "Save this code as <filename>src/main/java/org/hibernate/tutorial/util/HibernateUtil.java"
msgstr ""

#. Tag: para
#: tutorial.xml:452
#, no-c-format
msgid "This class not only produces the global <interfacename>org.hibernate.SessionFactory reference in its static initializer; it also hides the fact that it uses a static singleton. We might just as well have looked up the org.hibernate.SessionFactory reference from JNDI in an application server or any other location for that matter."
msgstr ""

#. 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 HibernateService to JNDI. Such advanced options are discussed later."
msgstr ""

#. 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 etc/ directory to your src directory, next to hibernate.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 ""

#. 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 ""

#. Tag: title
#: tutorial.xml:488
#, no-c-format
msgid "Loading and storing objects"
msgstr ""

#. Tag: para
#: tutorial.xml:490
#, 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() method:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:496
#, 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 ""

#. Tag: para
#: tutorial.xml:498
#, no-c-format
msgid "In <literal>createAndStoreEvent() we created a new Event object and handed it over to Hibernate. At that point, Hibernate takes care of the SQL and executes an INSERT on the database."
msgstr ""

#. Tag: para
#: tutorial.xml:505
#, 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 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."
msgstr ""

#. Tag: para
#: tutorial.xml:518
#, no-c-format
msgid "What does <literal>sessionFactory.getCurrentSession() do? First, you can call it as many times and anywhere you like once you get hold of your org.hibernate.SessionFactory. The getCurrentSession() method always returns the \"current\" unit of work. Remember that we switched the configuration option for this mechanism to \"thread\" in our src/main/resources/hibernate.cfg.xml? Due to that setting, the context of a current unit of work is bound to the current Java thread that executes the application."
msgstr ""

#. 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 ""

#. Tag: para
#: tutorial.xml:541
#, no-c-format
msgid "A <interface>org.hibernate.Session begins when the first call to 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 org.hibernate.Session from the thread and closes it for you. If you call getCurrentSession() again, you get a new org.hibernate.Session and can start a new unit of work."
msgstr ""

#. Tag: para
#: tutorial.xml:554
#, no-c-format
msgid "Related to the unit of work scope, should the Hibernate <interface>org.hibernate.Session be used to execute one or several database operations? The above example uses one org.hibernate.Session for one operation. However this is pure coincidence; the example is just not complex enough to show any other approach. The scope of a Hibernate org.hibernate.Session is flexible but you should never design your application to use a new Hibernate org.hibernate.Session for every database operation. Even though it is used in the following examples, consider session-per-operation an anti-pattern. A real web application is shown later in the tutorial which will help illustrate this."
msgstr ""

#. Tag: para
#: tutorial.xml:571
#, 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 ""

#. 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\""
msgstr ""

#. Tag: para
#: tutorial.xml:584
#, no-c-format
msgid "You may need to perform <command>mvn compile first."
msgstr ""

#. 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 ""

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

#. Tag: para
#: tutorial.xml:596
#, no-c-format
msgid "This is the <literal>INSERT executed by Hibernate."
msgstr ""

#. Tag: para
#: tutorial.xml:600
#, no-c-format
msgid "To list stored events an option is added to the main method:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:604
#, 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 ""

#. Tag: para
#: tutorial.xml:606
#, no-c-format
msgid "A new <literal>listEvents() method is also added:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:610
#, 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 ""

#. Tag: para
#: tutorial.xml:612
#, 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 Event objects with the data. You can create more complex queries with HQL. See  for more information."
msgstr ""

#. 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\""
msgstr ""

#. 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 ""

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

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

#. Tag: programlisting
#: tutorial.xml:646
#, 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 ""

#. 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"
msgstr ""

#. 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"
msgstr ""

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

#. Tag: para
#: tutorial.xml:660
#, no-c-format
msgid "Finally, add the new mapping to Hibernate's configuration:"
msgstr ""

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

#. 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 ""

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

#. 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 Person#getEvents. Multi-valued associations are represented in Hibernate by one of the Java Collection Framework contracts; here we choose a java.util.Set because the collection will not contain duplicate elements and the ordering is not relevant to our examples:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:689
#, 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 ""

#. 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 many-to-many association. Hence, we use Hibernate's many-to-many mapping:"
msgstr ""

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

#. Tag: para
#: tutorial.xml:706
#, no-c-format
msgid "Hibernate supports a broad range of collection mappings, a <literal>set being most common. For a many-to-many association, or n:m 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 table attribute of the set element. The identifier column name in the association, for the person side, is defined with the key element, the column name for the event's side with the column attribute of the many-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 ""

#. Tag: para
#: tutorial.xml:722
#, no-c-format
msgid "The database schema for this mapping is therefore:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:726
#, 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 ""

#. 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 ""

#. Tag: programlisting
#: tutorial.xml:737
#, 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 ""

#. 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 update() or save(); Hibernate automatically detects that the collection has been modified and needs to be updated. This is called automatic dirty checking. You can also try it by modifying the name or the date property of any of your objects. As long as they are in persistent state, that is, bound to a particular Hibernate 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 flushing. In our code, the unit of work ends with a commit, or rollback, of the database transaction."
msgstr ""

#. 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 detached). You can even modify a collection when it is detached:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:767
#, 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 ""

#. 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 ""

#. 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 save() method returns it (you might have to modify some of the previous methods to return that identifier):"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:786
#, 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 ""

#. 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 value types, and their instances 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 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 Address or MonetaryAmount class. In fact, in a Hibernate application all JDK classes are considered value types."
msgstr ""

#. 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 ""

#. 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 java.util.Set of java.lang.String instances:"
msgstr ""

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

#. Tag: para
#: tutorial.xml:825
#, no-c-format
msgid "The mapping of this <literal>Set is as follows:"
msgstr ""

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

#. 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 string. The lowercase name tells you it is a Hibernate mapping type/converter. Again the table attribute of the set element determines the table name for the collection. The key element defines the foreign-key column name in the collection table. The column attribute in the element element defines the column name where the email address values will actually be stored."
msgstr ""

#. Tag: para
#: tutorial.xml:847
#, no-c-format
msgid "Here is the updated schema:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:851
#, 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 ""

#. 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 ""

#. 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 ""

#. Tag: programlisting
#: tutorial.xml:864
#, 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 ""

#. 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 ""

#. 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 ""

#. 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 ""

#. Tag: programlisting
#: tutorial.xml:898
#, 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 ""

#. Tag: para
#: tutorial.xml:900
#, no-c-format
msgid "Now map this side of the association in <literal>Event.hbm.xml."
msgstr ""

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

#. 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 key and many-to-many swap in both mapping documents. The most important addition here is the inverse=\"true\" attribute in the set element of the Event's collection mapping."
msgstr ""

#. 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 ""

#. 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 Event in the unidirectional example? You add an instance of Event to the collection of event references, of an instance of Person. If you want to make this link bi-directional, you have to do the same on the other side by adding a Person reference to the collection in an Event. This process of \"setting the link on both sides\" is absolutely necessary with bi-directional links."
msgstr ""

#. 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 ""

#. Tag: programlisting
#: tutorial.xml:940
#, 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 ""

#. 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 ""

#. 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 INSERT and UPDATE statements (to avoid constraint violations). Making one side of the association inverse tells Hibernate to consider it a 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 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 ""

#. Tag: title
#: tutorial.xml:965
#, no-c-format
msgid "Part 3 - The EventManager web application"
msgstr ""

#. Tag: para
#: tutorial.xml:967
#, no-c-format
msgid "A Hibernate web application uses <literal>Session and Transaction almost like a standalone application. However, some common patterns are useful. You can now write an EventManagerServlet. This servlet can list all events stored in the database, and it provides an HTML form to enter new events."
msgstr ""

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

#. 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 doGet() method:"
msgstr ""

#. Tag: programlisting
#: tutorial.xml:983
#, 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 ""

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

#. 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 Session is opened through the first call to getCurrentSession() on the 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 ""

#. Tag: para
#: tutorial.xml:999
#, no-c-format
msgid "Do <emphasis>not use a new Hibernate Session for every database operation. Use one Hibernate Session that is scoped to the whole request. Use getCurrentSession(), so that it is automatically bound to the current Java thread."
msgstr ""

#. 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 ""

#. 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 Open Session in View. You will need it as soon as you consider rendering your view in JSP, not in a servlet."
msgstr ""

#. 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
#, 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.\");\n"
      "            }\n"
      "            else {\n"
      "                createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));\n"
      "                out.println(\"<b>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 ""

#. 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 ""

#. Tag: programlisting
#: tutorial.xml:1042
#, 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'/>
\");\n" " out.println(\"<input type='submit' name='action' value='store'/>\");\n" " out.println(\"</form>\");\n" " }]]>" msgstr "" #. Tag: para #: tutorial.xml:1044 #, no-c-format msgid "The <literal>listEvents() method uses the Hibernate Session bound to the current thread to execute a query:" msgstr "" #. Tag: programlisting #: tutorial.xml:1050 #, 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.