Hibernate learning notes (1)

xiaoxiao2021-03-06  41

Chapter 1. Quickly pick up in Tomcat

1.1. Start Hibernate Tour

This tutorial discusses how to install Hibernate 2.1 for the web program in the Apache Tomcat Servlet container. Hibernate can operate well in most mainstream J2EE application servers, or can be run as a stand-alone application. In this example database system is PostgreSQL 7.3, of course, it can also be easily replaced with one of the 16 databases supported by Hibernate.

The first step is to copy all the required runners to Tomcat. In this tutorial, we use a separate web program (WebApps / QuickStart). We must consider the global library file search path (Tomcat / Common / lib) and the class loader search path of this web application context (for JAR is WebApps / QuickStart / Web-INF / LIB, which is WebApps for Class files. / QuickStart / Web-INF / CLASSES. We refer to the Global ClassPath and the context classpath, respectively.

First, copy the JDBC driver to the database to the global class path. This is required by the DBCP (ie, Database Connection Pools) connected to Tomcat. For this tutorial, put the PG73JDBC3.JAR library file (corresponding to PostgreSQL 7.3 and JDK 1.4) to the global class loader path. If you use a different database, copy the corresponding JDBC driver). Don't copy anything else to the global type loader. Otherwise you may have troubles on some tools, such as log4j, commons-logging, etc. Remember to use each web application yourself to copy your own class library to WEB-INF / LIB, copy the configuration file CONFIGURATION / Property to WEB-INF / CLASSES below. These two directories are default the context-based path level. Hibernate is packaged into a JAR library. Hibernate2.jar files are placed in the context class with other library files of your application. At runtime, Hibernate also requires some third-party libraries, which are in the lib / directory of the Hibernate issued package. See Table 1.1. Copy the third-party library file you need to the context path. To configure database connections for Tomcat and Hibernate. That is to say Tomcat is responsible for providing the JDBC connection pool, Hibernate requests these connections through JNDI. Tomcat binds the connection pool to JNDI.

Table 1.1. Hibernate third-party library

Database Description DOM4J (Required) Hibernate needs to use DOM4J when parsing the XML configuration and XML map meta file. CGLIB (Required) Hibernate uses this code to generate library enhancement classes (in combination with Java reflex mechanism). Commons Collections, Commons Logging (Required) Hibernat uses multiple tool class libraries from the Apache Jakarta Commons project. ODMG4 (required) Hibernate provides an optional ODMG compatible persistence management interface. If you need a map collection, you need this class library, even if you are not using the ODMG API. We did not use the collection map in this tutorial, but no matter how this JAR copy is always good. Log4j (optional) Hibernate uses the Commons Logging API, the latter can use log4j as a mechanism to implement log. If you put the log4j library into the context class class, Commons logging uses log4j and its log4j.properties file found in the context class path. A Properties file containing an example in the Hibernate release package. So, copy the log4j.jar to your context path. Is other files not required? Please check the /lib/readme.txt file in the hibernate release package. This is a list of third-party libraries included in the Hibernate release package, always keep updates. You can find a list of all necessary or optional class libraries. Ok, now all the class libraries have been copied, let us add a database JDBC connection pool in Tomcat / conf / server.xml, and add a database JDBC connection pool resource statement.

factory

org.apache.commons.dbcp.basicDataSourceFactory

URL

jdbc: postgreSQL: // localhost / quickstart

driverclassname Org.postgreSql.driver

Username

QuickStart

Password

Secret

maxwait

3000

maxidle

100

maxactive

10

In this example we have to configure the context called QuickStart, which is located in the Tomcat / WebApp / QuickStart directory. To access any servlet, visit http: // localhost: 8080 / quickstart in your browser.

Tomcat In this configuration, Tomcat uses the DBCP connection pool, through the JNDI position: Java: Comp / Env / JDBC / QuickStart (in the string of Java: Comp / ENV / behind, in the string representing the JNDI position, the string of the Tomcat's Server. The Name value of ResourceParams in the XML file) provides JDBCConnections with buffer pools. If you encounter difficulties when you work when you work, please check the Tomcat documentation. If you get the JDBC driver Exception information, don't use Hibernate, test whether the JDBC connection pool itself is correct. Tomcat and JDBC tutorials can be found on the web.

The next step is to configure Hibernate to use the connection provided in the connection pool bound to JNDI. We use the Hibernate configuration in XML format. Of course, the way using the Properties file is also functional, nor is it particularly beneficial. We use XML configuration reasons because it is generally more convenient. XML configuration file is placed under the context type path (Web-INF / CLASSES), called Hibernate.cfg.xml:

PUBLIC "- // Hibernate / Hibernate Configuration DTD // EN"

"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

Java: Comp / Env / JDBC / QuickStart

false

Net.sf.hibernate.Dialect.postgreSqldiaAlaforct

We closed the log of the SQL command, telling Hibernate which SQL Database dialect (DIALET), how to get a JDBC connection (JNDI address bound by declaring data source pool). Dialect is required, because different databases and SQL "standards" have some access. Hibernate will take care of these differences, and the issued package contains dialects of all mainstream business and open source databases.

SessionFactory is the concept of hibernate, corresponding to a data store, if there are multiple databases, you can create multiple XML configuration files, and create multiple Configuration and SessionFactory objects in your program.

The last element in hibernate.cfg.xml declares that Cat.hbm.xml is a Hibernate XML mapping file that corresponds to the persistent class CAT. This file contains metadata that maps the POJO class to a database table (or multiple database tables). We will come back later to see this file. Let us write this POJO class first, then declare its map metadata.

1.2. First sustainable class

s Hibernate enables ordinary Java objects (Plain Old Java Objects, Pojos, sometimes called Plain ORDINARY JAVA OBJECTS) to become a persistent class. A POJO is very like JavaBean, attributes accessed through Getter and Setter methods, hidden the details of the internal implementation.

Package net.sf.hibernate.examples.quickstart;

PUBLIC CLASS CAT {

Private string id;

PRIVATE STRING NAME;

Private char sex;

PRIVATE FLOAT Weight;

Public cat () {

}

Public string getId () {

Return ID;

}

Public void setid (String ID) {

THIS.ID = ID;

}

Public string getname () {

Return Name;

}

Public void setname (String name) {

THIS.NAME = Name;

}

Public char getsex () {

Return SEX;

}

Public void setsex (char sex) {

THIS.SEX = SEX;

}

Public float getWeight () {

Return weight;

}

Public void setWeight (Float Weight) {

THIS.WEIGHT = Weight;

}

}

Hibernate is not restricted to the type of properties. All Java JDK types and original types (such as String, CHAR and FLOAT) can be mapped, including classes in the Java Collection Framework. You can map them into values, values, or associated with other entities. ID is a special property that represents the database identifier (primary key) of this class, which is required for entities similar to CAT.

The persistence class does not need to implement any special interface, nor does it need to inherit from a special persistent root. Hibernate also does not need to use any compile period, such as bytecode enhancement, which uses Java reflex mechanisms and runtime enhancements (via CGLIB). So, in Hibernate, POJO's class does not require any prerequisites, we can map it into database tables. 1.3. Mapping Cat

The Cat.hbm.xml mapping file contains metadata required for object / relationship mapping.

Metadata contains a statement of persistence classes and information that maps it to the database table with its properties (attribute as the value of the value or pointing to other entities).

Public "- // hibernate / hibernate mapping dtd // en"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

Generated by hibernate with the uuid pattern. ->

Each persistence class requires an identification attribute (actually, which represents a class representing the one-hand object, not the class representing the value object, the latter will be mapped as one of the one-handed object). This property is used to distinguish persistent objects: if cata.getid (). Equals (CATB.GetId ()) The result is true, two cats are the same. This concept is called the database identity. Hiernate has several different identifier generators for different occasions (including the sequence generator and Hi / LO high and low margin mode). We use the UUID generator here and specify the CAT_ID field of the CAT table (as the primary key of the table) to store the generated identifier value.

Other properties of CAT are mapped to the same table. For the Name property, we explicitly declare it to a database field. This is especially useful if the database schema is automatically generated by the mapping declaration using Hibernate's schemaExport tool (as SQL DDL instruction). All other properties are mapped with Hibernate's default, you will do this. The CAT table in the database looks like this:

Column | Type | Modifier

-------- ---------------------- -----------

CAT_ID | Character (32) | NOT NULL

Name | Character Varying (16) | NOT NULL

SEX | Character (1) |

Weight | Real |

Indexes: CAT_PKEY PRIMARY Key Btree (Cat_ID)

You can now create this table in your database, if you need to use the SchemaExport tool to automate this step, see Chapter 19, Toolbox Guide. This tool creates a complete SQL DDL, including table definitions, custom field type constraints, unique constraints, and indexes.

1.4. With the cat

We can now start Hibernate's session. We use it to access CAT from the database. First, we have to get a session (Hibernate work unit) from SessionFactory.

SessionFactory sessionFactory =

New Configuration (). configure (). BuildSessionFactory ();

SessionFactory is responsible for a database, and only one XML configuration file (hibernate.cfg.xml).

This tutorial's focus is to configure Tomcat's JDBC connection, bind to JNDI, and the basic configuration of Hibernate. You can write a servlet in any way, contain the following code, just make sure the sessionFactory is only created once. That is to say, you can't use it as an instance variable of your server. A good way is to use a static sessionFactory in auxiliary class, for example:

Import net.sf.hibernate. *;

Import net.sf.hibs. *;

Public class hibernateutil {

PRIVATE STATIC FINAL SESSIONFACTORY SESSIONFACTORY;

STATIC {

Try {

SESSIONFACTORY = New Configuration (). CONFIGURE (). BuildSessionFactory ();

} catch (hibernateException ex) {

Throw new runtimeException ("Exception Building "Factory: ex.getMessage (), EX);

}

}

PUBLIC Static Final Threadlocal session = new threadlocal ();

Public static session currentsession () throws hibernateException {

Session s = (session) session.get ();

// Open a new session, if this thread has none yetif (s == null) {

S = sessionFactory.openSession ();

Session.set (s);

}

Return S;

}

Public static void closesession () THROWS HibernateException {

Session s = (session) session.get ();

session.set (null);

IF (s! = null)

s.close ();

}

}

This class not only uses SessionFactory in its static properties, but also uses ThreadLocal to save the session for the current working thread.

Session is not a thread security, representing one operation between the database. SESSION is open through sessionFactory, after all work is complete, need to be closed:

Session session = hibernateutil.currents;

Transaction tx = session.begintransaction ();

Cat princess = new cat ();

Princess.setname ("Princess");

Princess.setSex ('f');

Princess.setWeight (7.4f);

Session.save (Princess);

TX.comMit ();

Hibernateutil.closesis ();

In session, each database operation is performed in a transaction, so you can separate different operations (even include read-only operations). We use Hibernate's Transaction API to get out of the underlying transaction strategy (this example is JDBC transaction). This way, if we need to deploy our program to a environment that is managed by the container (using JTA), we do not need to change the source code. Please note that we have no exceptions in the examples.

Please also note that you can call Hibernateutil.currentSession () as you want, you will get the same current thread for SESSION. You must ensure that session is turned off after your database transaction is complete, whether it is in your servlet code, or in servletfilter, HTTP results return.

Hibernate has different ways to retrieve objects from the database. The most flexible way is to use Hibernate Query Language (HQL), which is a language that is easy to learn, is an object-oriented powerful extension of SQL.

Transaction tx = session.begintransaction ();

Query Query = session.createQuery ("Select Cat from Cat AS Cat Where Cat.sex =: SEX");

Query.setCharacter ("SEX", 'F');

Iteerator it = query.Itemate (); it.hasnext ();) {

Cat Cat = (CAT) IT.Next ();

Out.println ("Female Cat:" Cat.getName ());

}

TX.comMit ();

Hibernate also provides an object-oriented-oriented query API to perform formulating type security queries. Of course, Hibernate uses PrePadedStatement and parameter binding in all interactions of the database. 1.5. Conclusion

In this short tutorial, we only portray the basic face of Hibernate. Note that we have not included the servlet related code in the example. You must write a servlet yourself and then insert you think the appropriate Hibernate code.

Remember Hibernate as a database access layer, which is closely related to your program. Generally, all other levels rely on a long-lasting mechanism. Be sure that you understand the meaning of this design.

1.6. to sum up

Several important parts of Hibernate:

Name Use Remarks Tomcat / conf / server.xml Add a database JDBC connection pool resource declaration: JNDi name, data source Factory, DBCP Database Connection Settings, DBCP Connection Pooling Options Hibernate.cfg.xml Declaration Hibernetate configuration: Main session-factory Configuration: Connection.DataSource, Show_SQL, Dialect, Dialect, Mapping Files, etc. Where mapping files are a list of mapping files (including metadata required for object / relationship mapping). The way Class Cat can be used in the way Class Cat can be used using XML and Properties files. Access to getter and setter methods, the details of the external implementation of the internal implementation Cat.hbm.xml declaration mapping file contains the metadata required for object / relationship mapping. Mainly include: Class Name, Table, persistent class objects and database field correspondence. SessionFactory Hibernate uses the SessionFactory class to complete the primary database operation: The sessionFactory class creates a new session based on hibernate.cfg.xml and tomcat / conf / server.xml, establish a database connection; according to the persistent class object Cat and mapping file Cat.hbm.xml Implement the operation of the data table in the database. This shows that Hibernate's work is determined according to the configuration file, which is very flexible.

转载请注明原文地址:https://www.9cbs.com/read-60499.html

New Post(0)