Java Enterprise Application-Comprehensive Solution for Hibernate

Source: Internet
Author: User
Tags database issues
Java Enterprise Application-Hibernate practical full solution-general Linux technology-Linux programming and kernel information, the following is a detailed description. Bromon originality, please respect copyright

Object Relative ing (ORM) is a hotspot in object-oriented development. It is used to solve the complexity and inconvenience of manual OR ing during JDBC development. The Entity Bean in EJB is well-known in this field-because of its advanced and famous, and because of its inefficiency. People who have experience developing entity beans may suffer from inefficiency in implementing remote interfaces. In many small projects, there is a lot of debate about whether the use of entity beans is worth the candle. A lightweight Persistence Solution may solve some problems. Hibernate is born here.

Hibernate is an intermediate layer. Its purpose is to map the relationships in the database to objects through certain rules, so that Java developers do not need to think too much about the underlying database issues, you only need to manage the data as you normally manage objects. When relational databases continue to occupy the market, it is impressive. In the field of data persistence, even lightweight solutions will be complex and cool, maybe just like Jay Chou's music. Before learning about it, you 'd better first think about the problems and inconveniences encountered during database development. Think about why a persistence layer is required to know the purpose of many operations, and why I want to do this? I don't want to give more details on this issue, because "for a long time ......" Such a sentence is usually long (sorry, I cannot beat it), which will cause a lot of wear and tear on my keyboard and enthusiasm. If I want to write a book, I will be happy to describe what is data persistence and what benefits it has. Come on.

First, you need to configure the environment, download Hibernate 2.1 (www.hibernate.org), and add *. jar under lib to classpath. Your Database JDBC driver should also be in classpath. Open hibernate. properties and configure the relevant information for the database you are using. For example, if I am using ms SQL Server, the configuration is as follows:

# Ms SQL Server

Hibernate. dialect net. sf. hibernate. dialect. SQLServerDialect
Hibernate. connection. driver_class com. microsoft. jdbc. sqlserver. SQLServerDriver
Hibernate. connection. url jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = zizz
Hibernate. connection. username sa
Hibernate. connection. password

Most of them have been written. You only need to remove the comment. I just modified the database name, account, and password. Create a database named zizz for backup.

Then copy the file to the root directory of your application.

We have talked about the ing many times. We should first look at how the ing is completed. Assume that the most simple application is to write a single message board with the most single function. The data designed includes the message number, name, content, and time of the message. It's easy enough. What are you going to do? I guess you should first create a database table named guestbook. No. This is not an object-oriented method. You may first consider it from the object perspective. Of course, we want every message to be presented as an object. Each object should have the following attributes: id, author, content, and time. I was too lazy to draw UML. The following class should be easy to understand:

// GuestBook. java
Package org. bromon. zizz;

Import java. util .*;

Public class GuestBook
{
Private int id;
Private String author;
Private String content;
Private Calendar time;

Private void setId (int id)
{
This. id = id;
}
Public int getId ()
{
Return (id );
}

Public void setAuthor (String author)
{
This. author = author;
}
Public String getAuthro ()
{
Return (author );
}

Public void setContent (String content)
{
This. content = content;
}
Public String getContent ()
{
Return (content );
}

Public void setTime (Calendar time)
{
This. time = time;
}
Public Calendar getTime ()
{
Return (time );
}
}


Basically, it is the simplest Bean. If you find it difficult, please wait for me on Mars first.

Note that the setId method is specified as private, because I want to use this field as the primary key. It is best to be automatically generated by the system, so it should not be specified by the user, this method is designed for Hibernate, so it is private.

How can I map this class to a database? Look at the magic of Hibernate and use an XML file to describe it. It should be named GuestBook. hbm. xml:

<? Xml version = "1.0 "? >
<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 2.0 // EN"
"'Target = _ blank & gthttp: // hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<Hibernate-mapping package = "org. bromon. zizz">
<Class name = "GuestBook" table = "guestbook" lazy = "true">
<Id name = "id" type = "integer" unsaved-value = "null">
<Column name = "id" SQL-type = "int" not-null = "true"/>
<Generator class = "identity"/>
</Id>

<Property name = "author" column = "author" not-null = "true" unique = "false"/>
<Property name = "content" column = "content" not-null = "true"/>
<Property name = "time" column = "time" not-null = "true"/>
</Class>
</Hibernate-mapping>

Although a little unfamiliar, but very easy to read, think carefully.

Let's write our application. Its function is to insert data:

// Operate. java
Package org. bromon. zizz;
Import net. sf. hibernate .*;
Import net. sf. hibernate. cfg .*;
Import net. sf. hibernate. tool. hbm2ddl .*;
Import java. util .*;

Public class Operate
{
Public static void main (String args [])
{
Try
{
Configuration cfg = new Configuration (). addClass (GuestBook. class );
SessionFactory sessions = cfg. buildSessionFactory ();
New SchemaExport (cfg). create (true, true );
Session session = sessions. openSession ();

GuestBook gb = new GuestBook ();
Gb. setAuthor ("Bromon ");
Gb. setContent ("message content ");
Gb. setTime (Calendar. getInstance ());

Transaction ts = session. beginTransaction ();
Session. save (gb );
Ts. commit ();
Session. close ();
} Catch (Exception e)
{
System. out. println (e );
}
}
}
Compile: javac? D. *. java
Run: java org. bromon. zizz. Operate

Go to the database and check that the table has been created and the data has been saved. If

New SchemaExport (). create (true, true );

Comment out, then the system will not create a table, but simply add new records to the existing table. Of course, if the table does not exist, an exception will occur.

You have seen the 5% magic of Hibernate, which is complex and powerful enough to handle complex applications.

One-to-one relationship
In most systems, it is impossible to have only one data table. Otherwise, it violates the original intention of relational databases. The relationship between a table and a table is complex and can be divided into several situations:

● One-to-one Association)
● One-to-Multiple Association)
● Multi-to-one Association)
● Multi-to-many Association)

In order. Assume that an example of one-to-one association is:
Table: person
Id (primary key)
Name
Email Address

Table: spouse
Id (foreign key)
Name

The person table stores user information, while spouse stores user spouse information. In general, the next person has only one spouse, which is suitable for one-on-one scenarios. If you are interested in the relationship, we can discuss this issue in the one-to-many and multi-to-one association. Maybe we can also find it in the many-to-many relationship ^_^ (animal !).

OK. Design POJO as follows:
The Person class is very simple:

/*
* Created on 2004-4-19
*/
Package org. bromon. zizz;

/**
* @ Author Bromon
*/
Public class Person
{
Private int id;
Private String name;
Private String email;

Public void setId (int id)
{
This. id = id;
}
Public int getId ()
{
Return (id );
}

Public void setName (String name)
{
This. name = name;
}
Public String getName ()
{
Return (name );
}

Public void setEmail (String email)
{
This. email = email;
}
Public String getEmail ()
{
Return (email );
}
}


Then write its ing rules. This should be understandable:
<? Xml version = "1.0 "? >
<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 2.0 // EN"
"'Target = _ blank & gthttp: // hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<Hibernate-mapping package = "org. bromon. zizz">
<Class name = "Person" table = "person" lazy = "true">
<Id name = "id" type = "integer" unsaved-value = "null">
<Column name = "id" SQL-type = "int" not-null = "true"/>
<Generator class = "identity"/>
</Id>

<Property name = "name" column = "name" not-null = "true" unique = "false"/>
<Property name = "email" column = "email" not-null = "false"/>
</Class>
</Hibernate-mapping>

So easy? Everything goes step by step. The following is the Souse class:

/*
* Created on 2004-4-20
*/
Package org. bromon. zizz;

/**
* @ Author Bromon
*/
Public class Spouse
{
Private int id;
Private String name;
Private Person person;

Public void setId (int id)
{
This. id = id;
}
Public int getId ()
{
Return (id );
}

Public void setName (String name)
{
This. name = name;
}
Public String getName ()
{
Return (name );
}

Public void setPerson (Person person)
{
This. person = person;
}
Public Person getPerson ()
{
Return (person );
}
}


Note the domain person in it. Its ing file:

<? Xml version = "1.0 "? >
<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 2.0 // EN"
"'Target = _ blank & gthttp: // hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<Hibernate-mapping package = "org. bromon. zizz">
<Class name = "Spouse" table = "spouse" lazy = "true">
<Id name = "id" type = "integer" unsaved-value = "null">
<Column name = "id" SQL-type = "int" not-null = "true"/>
<Generator class = "foreign">
<Param name = "property" & gtperson </param>
</Generator>
</Id>

<Property name = "name" column = "name" not-null = "true" unique = "false"/>
<One-to-one name = "person" class = "Person" cascade = "all" constrained = "true"/>
</Class>
</Hibernate-mapping>

The generator of id is a foreign key and associated with person. It is difficult to understand whether to specify a one-to-one relationship? Hibernate is indeed in line with our habits of thinking. It should be noted that this association is one-way, and people do not need to specify Spouse.

Perform the following operations on these two classes:

/*
* Created on 2004-4-20
*/
Package org. bromon. zizz;
Import net. sf. hibernate .*;
Import net. sf. hibernate. cfg .*;
Import net. sf. hibernate. tool. hbm2ddl .*;
/**
* @ Author Bromon
*/
Public class OperateSpouse
{
Public static void main (String args [])
{
Try
{
Configuration cfg = new Configuration (). addClass (Spouse. class );
Cfg. addClass (Person. class );
SessionFactory factory = cfg. buildSessionFactory ();
New SchemaExport (cfg). create (true, true );
Session session = factory. openSession ();

Person person = new Person ();
Person. setName ("bromon ");
Person. setEmail ("bromon@163.com ");

Spouse spouse = new Spouse ();
Spouse. setName ("who ");
Spouse. setPerson (person );

Transaction ts = session. beginTransaction ();
Session. save (person );
Session. save (spouse );
Ts. commit ();
Session. close ();
} Catch (Exception e)
{
System. out. println (e );
}
}
}


This example is very similar to the example in the first article. OK. Run the command and check the zizz database.

Relationship-to-One

Obviously, one-to-many or many-to-one relationships are very common phenomena in relational databases. The following uses the father-son example to demonstrate one-to-many relationships. The many-to-one relationship is similar, however, this is not suitable for our example. Otherwise, it will bring about ethical issues.

First, define the Child class:
/*
* Created on 2004-5-8
*/
Package org. bromon. zizz;

/**
* @ Author Bromon
*/
Public class Child
{
Private int id;
Private String name;
Private int fatherId;
Private Person father;

Public Child (){}

/**
* @ Return
*/
Public Person getFather ()
{
Return father;
}

/**
* @ Return
*/
Public int getFatherId ()
{
Return fatherId;
}

/**
* @ Return
*/
Public int getId ()
{
Return id;
}

/**
* @ Return
*/
Public String getName ()
{
Return name;
}

/**
* @ Param person
*/
Public void setFather (Person p)
{
Father = p;
}

/**
* @ Param I
*/
Public void setFatherId (int I)
{
FatherId = I;
}

/**
* @ Param I
*/
Public void setId (int I)
{
Id = I;
}

/**
* @ Param string
*/
Public void setName (String string)
{
Name = string;
}

}

Here, fatherId is a foreign key that associates with the id field of the person table.

The following is the Child ing file Child. hbm. xml:
<? Xml version = "1.0 "? >
<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 2.0 // EN"
"'Target = _ blank & gthttp: // hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<Hibernate-mapping package = "org. bromon. zizz">
<Class name = "Child" table = "child" lazy = "true">
<Id name = "id" type = "integer" unsaved-value = "null">
<Column name = "id" SQL-type = "int" not-null = "true"/>
<Generator class = "identity"/>
</Id>

<Property name = "name" column = "name" not-null = "true" unique = "false"/>
<Role-to-one name = "father" column = "fatherid"/>

</Class>
</Hibernate-mapping>
Note that fatherId is not mapped as a property, but is used in the role-to-one declaration.

Modify Person .. java and add the following code:

Import java. util .*;

Private Set children = new HashSet ();
/**
* @ Return
*/
Public Set getChildren ()
{
Return children;
}
/**
* @ Param set
*/
Public void setChildren (Set set)
{
Children = set;
}

Then modify Person. hbm. xml to map the added code:

<Set name = "books" lazy = "true" inverse = "true" cascade = "all">
<Key column = "fatherid"/>
<One-to-learn class = "Child"/>
</Set>

The key column here is the foreign key of the child table, and the inverse must be specified as true.

The following is an operation to query the records with id = 1 in the person table. As the parent of a child, add a new record to the child table.

/*
* Created on 2004-5-8
*/
Package org. bromon. zizz;
Import net. sf. hibernate .*;
Import net. sf. hibernate. cfg .*;
Import net. sf. hibernate. tool. hbm2ddl .*;
/**
* @ Author Bromon
*/
Public class OperateChild
{
/**
* @ Param args
*/
Public static void main (String args [])
{
Try
{
Configuration cfg = new Configuration (). addClass (Person. class );
Cfg. addClass (Child. class );
SessionFactory sessions = cfg. buildSessionFactory ();
New SchemaExport (cfg). create (true, true );
Session session = sessions. openSession ();

Child c = new Child ();

/* Query q = session. createQuery ("from org. bromon. zizz. Person as p where p. id = 1 ");
Person p = (Person) q. list (). get (0 );*/

Person p = (Person) session. find ("from org. bromon. zizz. Person as p where p. id =? ", New Integer (1), Hibernate. INTEGER). get (0 );
System. out. println (p. getName ());
C. setName ("andy ");
C. setFather (p );

Transaction ts = session. beginTransaction ();
Session. save (c );
Ts. commit ();
Session. close ();
} Catch (Exception e)
{
System. out. println (e );
}
}
}

The commented out part is another HQL query method. In this example, we can see that the object query is very easy. You do not need to encapsulate the data yourself, and it is also easy to modify or delete the object:

// Get an object
Query q = session. createQuery ("from org. bromon. zizz. Person as p where p. id = 1 ");
Person p = (Person) q. list (). get (0 );

// Modify data
P. setName ("Mr Smith ");

// Save data
Session. save (p );
Session. flush ();

// Delete data
Session. delete (p );
Session. flush ();
Related Article

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.