Hibernate application (1): The first hibernate Application

Source: Internet
Author: User

I have heard that hibernate has been around for a long time, but it has not been close to it until recently. I saw a training PPT in xiangji a long time ago. It said that hibernate is applied to the persistent layer, and Hibernate and persistence seem to be in a pair. So what is hibernate used for? What are its advantages? We will not go into details about some concepts of hibernate, such as ORM and persistence. We will directly start to build one of our hibernate applications (usually our applications are Web applications. Here I will build a web project, however, it is easier to understand that I use Java application for running, because in Web applications, Hibernate will be used together with frameworks such as spring ).

What do we need to prepare to build a hibernate application? First of all, I will go to the official website to release the next hibernate package. My website is 3.0. Next, follow these steps:

1. prepare a configuration file hibernate. cfg. XML, which defines some basic attributes, such as database connection parameters and the address of the ing file. This file is required, hibernate will first parse and load this XML file and store it in the cache. My hibernate. cfg. the XML content is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>

<! Doctype hibernate-configuration public "-// hibernate/hibernate configuration DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<Hibernate-configuration>

<Session-factory>

<Property name = "connection. url">

JDBC: mysql: // localhost: 3306/test

</Property>

<Property name = "connection. driver_class">

Com. MySQL. JDBC. Driver

</Property>

<Property name = "connection. username"> root </property>

<Property name = "connection. Password"> 111111 </property>

<Property name = "dialect">

Org. hibernate. dialect. mysqldialect

</Property>

<Property name = "show_ SQL"> true </property>

<Mapping Resource = "cN/edu/Hust/CM/mypack/customer. HBM. xml"/>

</Session-factory>

</Hibernate-configuration>

2. I am using a MySQL database. Different DBMS may vary in some places. Assume that I have a table in the database to store basic customer information. I have created a customer table. The schema is as follows:

Create Table 'customer '(

'Id' bigint (11) not null default '0 ',

'Name' varchar (40) not null default '',

'Email 'varchar (128) Character Set Latin1 not null default '',

'Password' varchar (8) Not null default '',

'Phone' int (11) default '0 ',

'Address' varchar (255) default null,

'Sex' char (1) Character Set Latin1 default null,

'Is _ married' bit (1) default null,

'Description' text,

'Image' blob,

'Birthday' date default null,

'Registered _ time' timestamp null default current_timestamp

)

3. Create a customer. Java file (this is what we call the persistence class)

 

Package cn.edu. HUST. cm. mypack;

 

Import java. Io. serializable;

Import java. SQL. date;

Import java. SQL. timestamp;

 

/**

* @ Author zhukai

*

*/

Public Class Customer implements serializable {

Private long ID;

Private string name;

Private string email;

Private string password;

Private int phone;

Private Boolean married;

Private string address;

Private char sex;

Private string description;

// Private byte [] image;

Private date birthday;

Private timestamp registeredtime;

/**

* Hibernate requires that the persistence class provide a default constructor without parameters.

*/

Public customer (){

// Todo auto-generated constructor stub

}

Public String getaddress (){

Return address;

}

Public void setaddress (string address ){

This. Address = address;

}

Public String getdescription (){

Return description;

}

Public void setdescription (string description ){

This. Description = description;

}

Public date getbirthday (){

Return birthday;

}

Public void setbirthday (date birthday ){

This. Birthday = birthday;

}

Public String getemail (){

Return email;

}

Public void setemail (string email ){

This. Email = Email;

}

Public long GETID (){

Return ID;

}

Public void setid (long ID ){

This. ID = ID;

}

Public Boolean ismarried (){

Return married;

}

Public void setmarried (Boolean married ){

This. Married = married;

}

Public String getname (){

Return name;

}

 

Public void setname (string name ){

This. Name = Name;

}

Public String GetPassword (){

Return password;

}

Public void setpassword (string password ){

This. Password = password;

}

Public int getphone (){

Return phone;

}

Public void setphone (INT phone ){

This. Phone = phone;

}

Public timestamp getregisteredtime (){

Return registeredtime;

}

Public void setregisteredtime (timestamp registeredtime ){

This. registeredtime = registeredtime;

}

Public char getsex (){

Return sex;

}

Public void setsex (char sex ){

This. Sex = sex;

}

}

Note that this class uses the standard JavaBean format. We usually need to follow this standard to construct our persistence class.

4. Configure the ing File

Generally, the ing file adopts a naming rule: Class Name. HBM. XML, and the class file of this class are placed under a directory. My customer. HBM. xml file is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>

<! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<Hibernate-mapping>

<Class name = "cn.edu. HUST. cm. mypack. Customer" table = "customer">

<ID name = "ID" type = "long">

<Column name = "ID"> </column>

<Generator class = "increment"> </generator>

</ID>

<Property name = "name" type = "string">

<Column name = "name" not-null = "true"> </column>

</Property>

<Property name = "email" type = "string">

<Column name = "email" not-null = "true"> </column>

</Property>

<Property name = "password" type = "string">

<Column name = "password" not-null = "true"> </column>

</Property>

<Property name = "phone" type = "integer">

<Column name = "phone" not-null = "true"> </column>

</Property>

<Property name = "Address" type = "string">

<Column name = "Address"> </column>

</Property>

<Property name = "sex" type = "character">

<Column name = "sex"> </column>

</Property>

<Property name = "married" type = "Boolean">

<Column name = "is_married"> </column>

</Property>

<Property name = "Description" type = "string"> </property>

<Property name = "Birthday" type = "date">

<Column name = "Birthday"> </column>

</Property>

<Property name = "registeredtime" type = "timestamp">

<Column name = "registered_time"> </column>

</Property>

</Class>

</Hibernate-mapping>

Note: This file is critical. It relates to our persistence class and the table corresponding to it in the database. The specific relationship is shown in:

 

The ing file is like a dictionary. When hibernate inserts data into the database, it "queries" to know which column the attribute corresponds to in the database, when the data is read from the database and assigned to the persistent class, the "query" is used to know which attribute of the column corresponds to the persistence class. This metaphor is not very appropriate, because not all attributes of the persistence class are directly matched with the table fields.

OK, now the preparations are ready. You can write a program to use hibernate. My main program is running as follows:

Package cn.edu. HUST. cm. mypack;

 

Import javax. servlet .*;

Import org. hibernate .*;

Import org. hibernate. cfg. configuration;

 

 

Import java. Io .*;

Import java. SQL. date;

Import java. SQL. timestamp;

Import java. util. iterator;

Import java. util. List;

Public class businessService {

 

Public static sessionfactory;

/* Static block, which is executed when the class is loaded. It is used to initialize Hibernate and create sessionfatory instance */

Static {

Try {

Configuration configuration = new configuration ();

Sessionfactory = configuration. Configure (). buildsessionfactory ();

}

Catch (exception e ){

E. printstacktrace ();

}

Finally {

}

}

/* Default constructor */

Public businessService (){

}

Public static sessionfactory getsessionfactory (){

Return sessionfactory;

}

/**

* This method is the test entry. test each method.

*/

Public void test (){

Customer customer = new customer ();

Customer. setname ("Zhu kai ");

Customer. setemail ("xiaozhu87487705@163.com ");

Customer. setpassword ("19840827 ");

Customer. setphone (1234 );

Customer. setaddress ("No. 1037, Xiaoyu Road, Wuhan City, Hubei Province ");

Customer. setsex ('M ');

Customer. setmarried (false );

Customer. setdescription ("Mango network employee ");

Customer. setbirthday (new date (14*365*24*3600*1000 ));

Customer. setregisteredtime (New timestamp (36*365*24*3600*10000 ));

Savecustomer (customer );

Findallcustomers ();
Loadandupdatecustomer (customer. GETID ());
Deleteallcustomers (customer );

}

/**

* Store a customer object in the database

*/

Public void savecustomer (customer ){

Session session = sessionfactory. opensession ();

Transaction Tx = NULL; // The initial value must be assigned to the local variable.

Try {

Tx = session. begintransaction ();

// Start the transaction

Session. Save (customer );

TX. Commit ();

}

Catch (exception e ){

If (TX! = NULL) Tx. rollback ();

E. printstacktrace ();

}

Finally {

Session. Close ();

}

}

/**

* Query all the persistent objects in the data and display their basic information.

*/

Public void findallcustomers (){

Session session = sessionfactory. opensession ();

Transaction Tx = NULL;

Try {

Tx = session. begintransaction ();

// Start the transaction

Iterator customers = session. createquery ("from customer"). List (). iterator ();

While (customers. hasnext ()){

Customer cs = (customer) MERs. Next ();

System. Out. println ("name:" + CS. getname ());

System. Out. println ("Gender:" + CS. getsex ());

System. Out. println ("Email:" + CS. getemail ());

System. Out. println ("Marital status:" + CS. ismarried ());

}

TX. Commit ();

}

Catch (exception e ){

If (TX! = NULL) Tx. rollback ();

E. printstacktrace ();

}

Finally {

Session. Close ();

}

}

/**

* Load and modify the specified Persistent Object

* @ Param ID: ID of the object OID

*/

Public void loadandupdatecustomer (long ID ){

Session session = sessionfactory. opensession ();

Transaction Tx = NULL;

Try {

Tx = session. begintransaction ();

// Start the transaction

Customer cs = (customer) Session. Load (customer. Class, ID );

CS. setaddress ("Shenzhen City, Guangdong Province ");

TX. Commit ();

}

Catch (exception e ){

If (TX! = NULL) Tx. rollback ();

E. printstacktrace ();

}

Finally {

Session. Close ();

}

}

Public void deleteallmers MERs (customer C ){

Session session = sessionfactory. opensession ();

Transaction Tx = NULL;

Try {

Tx = session. begintransaction ();
// Start the transaction
Session. Delete (c );
// Query = session. createquery ("delete from customer ");
// Query.exe cuteupdate ();
TX. Commit ();

}

Catch (exception e ){

If (TX! = NULL) Tx. rollback ();

E. printstacktrace ();

}

Finally {

Session. Close ();

}

}

/**

* @ Param ARGs

*/

Public static void main (string [] ARGs ){

BusinessService BS = new businessService ();

BS. Test ();

Sessionfactory. Close ();

}

}

In this way, our first hibernate application will be successful. As for the usage of various classes and interfaces in hibernate, such as session and sessionfactory interfaces, we will continue to introduce them in future studies, it is mainly because I have not studied these classes well, ^ _ ^.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.