Java Enterprise Application-Comprehensive Solution for Hibernate

Source: Internet
Author: User
Tags database issues

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:

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

& Lt hibernate-mapping package = "org. bromon. zizz" & gt
& Lt class name = "GuestBook" table = "guestbook" lazy = "true" & gt
& Lt id name = "id" type = "integer" unsaved-value = "null" & gt
& Lt column name = "id" SQL-type = "int" not-null = "true"/& gt
& Lt generator class = "identity"/& gt
& Lt/id & gt

& Lt property name = "author" column = "author" not-null = "true" unique = "false"/& gt
& Lt property name = "content" column = "content" not-null = "true"/& gt
& Lt property name = "time" column = "time" not-null = "true"/& gt
& Lt/class & gt
& Lt/hibernate-mapping & gt

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.

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.