Hibernate learning notes

xiaoxiao2021-03-06  42

Hibernate learning notes

1. Hibernate introduction

Hibernate is an O / R Mapping of an open source, which makes a lightweight object package for JDBC, allowing Java programmers to operate the database as you want to use objects to manipulate the database.

Hibernate is an object / relational database mapping tool for Java environments. Object / Relational Mapping (ORM) This term represents a technique to map objects represented by the object model to the SQL-based relationship model structure. Hibernate not only manages the mapping of the Java class to the database table, but also provides data query and acquisition data.

The time of manually use SQL and JDBC processing data when developing. Hibernate's goal is to liberate 95% of the programming tasks related to developers' usual data persistence.

Hibernate development preparation needs to prepare tools:

Hibernate Tools, Downloads: http://www.hibernate.org.cn/download/

Hibernate-

2.1.2

.zip, then decompress it. It is assumed to put it in the C: /Hibernate-2.1 directory (we set the environment variable hibernate_home = C: /Hibernate-2.1). Let's take a look at Hibernate's bag, first there is a hibernate in% hibernate_home% directory.

2.jar, the package is the Hibernate toolkit we need to use for Hibernate development. Of course, Hibernate itself needs other libs support, these support packs are in% hibernate_ho

ME% / lib under. Please see Table 1-1, Hibernate's third-party library

Library name

Description

DOM4J (required)

Hibernate needs to use DOM4J when parsing XML configuration and XML map meta files.

CGLIB (required)

Hibernate uses this code to generate library enhancement classes (in combination with Java reflex mechanism).

Commons Collection, Commons Logging, COMMONS logging

Hibernat uses multiple tool class libraries from the Apache Jakarta Commons project.

Odmg4

Hibernate provides an optional ODMG compatible persistent management interface. If you need a map collection, you need this class library, even if you are not using the ODMG API.

Log4j

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.

Other files are not required

Please check the /lib/readme.txt file in the hibernate release package. This is an

The list of third-party libraries included in the Hibernate release package is always updated. You can find a list of all necessary or optional class libraries.

Table 1-1

2. Hibernate configuration

First, let's take a look at the Hibernate global configuration file, this configuration file can have two forms, each form can complete the configuration of Hibernate, respectively, Hibernate.properties or hibernate.cfg.xml, this file needs to be placed in context The path under the path (assuming in a web application, you need to put it under Web-INF / CLASSES), but please note that although Hibernate officials must put it in this directory, it is actually below other paths, only need When you add the path to the configuration file, you can add the path to the configuration file. With regard to the content of the configuration file, you can see the Hibernate.properties file in the% hibernate_home / src directory, and explain the meaning of its meaning, you can see: http://www.javajia.com/Article.php? Id = 901

Http://www.hibernate.org.cn/53.html

Some other preparations are required before entering the Hibernate routine. Download Application Server JBoss

3.2.6

The download address is:

http://voxel.dl.sourceforge.net/sourceforge/jboss/jboss-3.2.6.zip

Download mysql

5.0.0

The download address is:

http://mysql.linuxforum.net/downloads/mysql-5.0/mysql-5.0.0a-alpha-win.zip

And the JDBC database connection package for the MySL database, download address:

http://dev.mysql.com/get/downloads/connector-j/mysql-connector-java-3.1.4-beta.zip

Of course, you must also make sure you have already installed J2SDK

1.4.2

If not please download and install:

Http://java.sun.com/j2sk/1.4.2/download.html

Also, you must be sure, you have set up Java_Home, JBoss_Home, ClassPath, etc. Environment variables. It is best to put the MySQL JDBC connection package, put it in% JBoss_HOME% /

SERVER / DEFAULT / LIB below.

In addition, you need to create a TEST library in the MySQL database, and create a table called Courses in this library, which creates statements:

Create Database if not exists `test`;

Use `test`;

Drop Table if EXISTS `COURSES`;

Create Table `Courses` (

`Courseid` VARCHAR (32) Not null default '',

`Name` VARCHAR (32) Default Null,

Primary key (`courseid`)

ENGINE = myisam default charSet = latin1;

INSERT INTO `Courses` Values

('2313213213', 'eeeeeee'),

('12345656', 'jacky'),

('Bonnie', 'Bonnie');

This creates the tables and test data required for our routines. In addition, we also need to configure the data source of JBoss. Before you, start JBoss, if you don't start properly, check the environment variable configuration, or view the JBoss website. Find the% jboss_home% / server / default / deploy directory to see if there is mysql data source profile for MySQL-DS.xml in this directory. If you do not create this file, the file is as follows:

mysqlds

JDBC: MySQL: // Localhost: 3306 / Test

Org.gjt.mm.mysql.driver

root

This is configured with JBoss JDBC data sources. Its name is mysqlds. Start JBoss, pay attention to the console output information, has set the data source to the JAVA: / mysqlds JNDI name.

3. Hibernate routine

a) Open JBuilder to create a new project and name it TestHibernate. then

Put the% hibernate_home / hibernate2.jar and the% hibernate_home% / lib (you can also put all the packages) under a JBuilder Library, introduce this library into the ClassPath of the TestHibernate project. This introduces all the packages required by all Hibernate.

b) Establish the first sustainable class. Create a category, set it with its package com.hibernate

And name it Cours.java, which is as follows:

Package com.hibernate;

Import java.util.set;

/ **

* Represents classes of the COURSE table in Hibernate.

* /

Public Class Cours

{

/ ** Each property and a field of the table correspond to ** /

PRIVATE STRING COURSEID;

PRIVATE STRING NAME;

/ ** Students indicate students in Course, will only be used later, no matter whether it is ** /

PRIVATE SET STUDENTS;

/ ** Access method for properties ** /

Public void setCourse (String string) {

Courseid = String;

}

Public string getCourseId () {

Return CourseId;

}

Public void setname (String name) {

THIS.NAME = Name;

}

Public string getname () {

Return this.name;

}

Public void setStudents (SET Stud) {

THIS.STUDENTS = STUD;

}

Public set getstudents () {

Return this.students;

}

}

c) Establish a JSP page to generate the DEFAULTROOT directory structure, compile the Java source file.

d) This time we can find the directory where the JBuilder project is located, find the classes directory below the default, and create a hibernate configuration file hibernate.cfg.xml in this directory, now let's see the file.

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

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

Java: / mysqlds

false

Net.sf.hibernate.dialect.mysqldiaAlaforct

Org.jnp.interfaces.namingContextFactory

JNP: // localhost: 1099 /

First we must ensure that Hibernate will connect to the MySQL database, refer to the Hibernate configuration document mentioned above, which requires us to configure hibernate.diaalect dialect properties, which means that Hibernate needs to connect to the database type, where we are set to mysql type. Set hibernate.diact to NET.SF.HIBERNATE.DIALECT.MYSQLDIALECT.

And the data source of the database is accessed, we are set here into java: / mysqlds. We need to pay attention to Hibernate comes with a connection pool configuration solution (Hibernate.Properties):

Hibernate.Dialev Net.sf.hibernate.dialect.mysqldiaLect

Hibernate.Connection.driver_class com.mysql.jdbc.driver

Hibernate.Connection.URL JDBC: MySQL: /// TEST

Hibernate.Connection.username root

Hibernate.connection.password

If you go to study the source code of Hibernate, you will find that the Hibernate comes with the connection pool solution is a very original connection pool, so we are here. Hibernate has three connection findings: Hibernate comes with the DBCP connecting pool of the Hibernate tape, the connection pool of the App Server. Of course, we choose the last solution that uses App Server to provide a connection pool. The hibernate.show_sql property is to let the user see the output of the SQL statement through the console when the user can purchase in the debugger, so that the user debugs, here we have chosen the output, of course, you can also open the output, as long as this property Set to true value.

For hibernate.jndi.class and hibernate.jndi.URL properties, this property is when you want to directly call resources under different JVMs directly from the remote client, you need to find JNDI resources through these two properties. It is set here to find the resources under this service through the NamingContextFactory provided by JNP. But you need to pay attention to: JBoss configuration DataSource JNDI name is Java: / mysqlds, JBoss is called calls that do not support remote clients to its JNDI resource. So here these two attributes have no practical significance, and when we replace JBoss to WebLogic, you can get server resources in additional JVM at the remote client by looking up the JVM, such as connectivity. Pool data source.

For mapping mapping properties, this is to notify hibernate, let it know that there is already a mapping file to map the table in the database, this file name is cours.hbm.xml.

For more configuration information about hibernate.cfg.xml or hibernate.properties file, please refer to the reference address mentioned above.

e) Let's take a look at the courshbm.xml mentioned in the next section. Similarly, this file needs

Put it in the default / classes directory. The content of this file is as follows:

"- // Hibernate / Hibernate mapping DTD 2.0 // en"

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

Name = "com.hibernate.cours"

Table = "coursees"

Dynamic-update = "false"

>

Name = "courseid"

COLUMN = "courseid"

TYPE = "string"

Unsaved-value = "any"

>

Name = "name"

TYPE = "string"

Update = "true"

INSERT = "True"

COLUMN = "Name"

/>

Let us first look at the Class node, which describes a table in the database corresponding to one of the sustainable classes we created (this persistence class is similar to JavaBean, accessed through Getter and Setter.). Here we can see that Name is a database table for a COM.HIBERNATE.COURS corresponding to table, the Dynamic-Update property is used to identify if the Update's SQL statement is dynamically generated during runtime, and it updates those Changed fields. Here we don't need to pay too much attention to this property. Second, observe the ID child node, the node represents the key field of the table, name = "courseid" indicates that the Attribute property of the COURSES table master keyword in the com.hibernate.cours class is CourseId. The corresponding field is column = "courseid", type type = "string"

And for a specific identity attribute value for Unsaved-value = "any", used to mark the instance is just

Just created, not yet saved. This can distinguish this example and instances that have been loaded from previous sessions but unable persistently. Node Defines the generation rules of the primary keyword, Assign indicates that the primary key generation rule assigns a primary keyword identifier for the user before SAVE. Keyword generation rules have the following types:

increment

Used to generate unique identifiers for long, short, or int types. It can only be used when there is no other process to insert data into the table. Don't use it under the cluster.

Identity

Support for the built-in identity fields of DB2, MySQL, MS SQL Server, Sybase, and Hypersonics QL. The returned identifier is LONG, SHORT, or INT type.

SEQUENCE (sequence)

In DB2, PostgreSQL, Oracle, SAP DB, MCKOI uses sequence (Generator) in InterBase. The returned identifier is LONG, SHORT, or INT type.

Hilo (high low)

Use a high / low algorithm to efficiently generate LONG, SHORT or INT type identifiers. Given a table and field (the default is hibernate_unique_key and next) as a high source. The identifier generated by the high / low algorithm is only unique in a particular database. This generator is not used in the connection obtained by JTA or the user supplies it.

SEQHILO (using a sequence of high low)

Use a high / low algorithm to efficiently generate LONG, SHORT, or INT type identifiers, given a name of a database sequence (SEQUENCE).

UUID.HEX

Generate a string type identifier with a 128-bit UUID algorithm. Unique in a network (using IP address). UUID is encoded as a 32-bit 16-en-numeric string.

uuid.string

Use the same UUID algorithm. UUID is encoded a string consisting of 16 character long ASCII characters. Can't use in the PostgreSQL database

Native (local)

The ability to select Identity, Sequence, or Hilo according to the ability of the underlying database.

Assigned (program setting)

Let the application assign an object to the object before save ().

FOREIGN (external reference)

Use another identifier of the other associated object. Use .

Hibernate describes the properties of other non-key fields with the Property node, f) We need to create a HibernateUtil class as a tool class for getting the session.

We can now start Hibernate's session. We use it to access Cours 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). 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

SessionFactory: " ex.getMessage (), EX);

}

}

PUBLIC Static Final Threadlocal session = new threadlocal ();

Public static session currentsession () THROWS HIBERNATEXCEPTION

{

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

// Open a new session, if this thread HAS NONE YET

IF (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 ();

Couss course = new cours ();

Course.SetCourseId ("Aaaaaaaa");

Course.setname ("bbbbbbb") session.save (prinities);

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 you need to deploy our program to a container management transaction

In the environment (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 as you want.

CurrentSession (), you will get the same current thread for each time. 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.

g) Creating a way to access the Bean class to encapsulate the method of calling the Hibernate to access the database. Here we do our best to define this method as StoreAccessBean.java. The source file is as follows:

Package com.hibernate;

Import net.sf.hibernate.hibernateException;

Import net.sf.hibernate.Session;

Import net.sf.hibernate.transaction;

Import java.util.iterator;

Import java.util.hashtable;

Import javax.naming.context;

Import javax.naming.initialcontext;

Import javax.sql.datasource;

Public class storeAccessBean {

Public storeAccessBean () {

}

Public Void AddStoreAccess (Cours Store) {

Try {

Session session = hibernateutil.currents;

Transaction trans = session.begintransaction ();

Session.save (store);

TRANS.COMMIT ();

Hibernateutil.closesis ();

}

Catch (Exception EX) {

EX.PrintStackTrace ();

}

}

Public iterator getAllcourses () THROWS HIBERNATEXCEPTION

{

String queryString = "Select StoreAccess from StoreAccess as StoreAccess";

Session session = hibernateutil.currents;

Net.sf.hibernate.Query Query = session.createQuery (queryString);

Iterator it = query.Itemate ();

Hibernateutil.closesis ();

Return IT;

}

}

There are two methods in this class, one is a method of adding a data, and the other is a method of queries.

Finally, compile all files. Add the following code to the new JSP just now:

com.hibernate.cours access = new com.hibernate.cours (); access.setCourseId ("aaaaaaaa"); Access.setname ("Bbbbbb");

com.hibernate.storeAccessBean bean = new com.hibernate.storeAccessBean ();

Finally, the WAR package is made, deployed into the% jboss_home% / server / default / deploy directory, start JBoss, access the established JSP page, then see if there is more records in the database, indicating that the routine is successful.

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

New Post(0)