此内容没有您所选择的语言版本。
2.3.5. Hibernate Configuration
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"
Note
We do this do that the data remains between runs.
We will utilize the Maven exec plugin to launch the HSQLDB server by running:
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.
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
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.
Warning
The built-in Hibernate connection pool is not intended for production use.
For Hibernate's configuration, we can use a simple
hibernate.properties file, a more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file:
Note
Notice that this configuration file specifies a different DTD
You configure Hibernate's
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.
The first four
property elements contain the necessary configuration for the JDBC connection. The dialect property element specifies the particular SQL variant Hibernate generates.
Note
Hibernate is able to correctly determine which dialect to use in most cases.
Hibernate's automatic session management for persistence contexts is particularly useful in this context. The
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.
Save this file as
hibernate.cfg.xml into the src/main/resources directory.