Hello word of hibernate (written by experts in China)

Source: Internet
Author: User
Finally, I feel a little bit about getting started with hibernate. It is convenient for overseas learners to give a simple entry example.
If you have used other persistent architectures and switched to hibernate, it is actually very easy. I will not talk about some principles,
Robbin is definitely better than me. Go to the essence edition.
All I have given is a simple example and setting method that I wanted when I first got started with hibernate.
I have never found it, so I am here to show it to you (just give an intuitive sense of getting started, huh, huh)

First of all, you must create a project.

Then, go to Project Properties> paths> required libraries> Add> New. Here, the hibernate class library is defined to include all the jar packages under the Lib of hibernate. Of course, the hibernate2.jar file is required.
Then go all the way to OK.

Hibernate. Properties
Find
Copy it to the src directory of your project.
(What, your project does not have the src directory. If you create a new class, you have the src directory)

This is the development environment of hibernate under JB.

Then set your database connection in hibernate. properties.
Hypersonicsql by default

Well, what you want to do most is actually very simple.
Creates a message. Java class.
The Code is as follows:

Code:
Package hello;

Import java. Io. serializable;

/**
* @ Author getdown
* @ Version 1.0
*/

Public class Message implements Serializable {
Private Long id;
Private String text;
// Define a simple linked list pointing to another Message
Private Message nextMessage;
Public Message (){}

Public Message (Long id ){
This. id = id;
}

Public Message (String text ){
This. text = text;
}

Public Message (Long id, String text ){
This. id = id;
This. text = text;
}

Public Long getId (){
Return id;
}

Private void setId (Long id ){
This. id = id;
}

Public String getText (){
Return text;
}

Public void setText (String text ){
This. text = text;
}

Public Message getNextMessage (){
Return nextMessage;
}

Public void setNextMessage (Message nextMessage ){
This. nextMessage = nextMessage;
}

}

Next, the hibernate configuration file Message. hbm. xml corresponding to this class

Code:
<? Xml version = "1.0"?>

<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 2.0 // EN"
Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>
<Hibernate-mapping>
<! -- Define the correspondence between classes and tables -->
<Class
Name = "hello. Message"
Table = "Messages"
>
<! -- Define the ID field and the ID generation policy. identity is used here -->
<Id name = "id"
Column = "MESSAGE_ID"
>
<Generator class = "identity"/>
</Id>
<! -- Define the text field -->
<Property
Name = "text"
Type = "string">
<! -- Define the method for generating text fields in the database -->
<Column
Name = "TEXT"
Length = "100"
Not-null = "true"
/>
</Property>
<! -- Define the correspondence between object associations and associated fields -->
<Role-to-one
Name = "nextMessage"
Cascade = "all"
Column = "NEXT_MESSAGE_ID"
/>
</Class>
</Hibernate-mapping>

Then there is the test class.

Code:
Package hello;

Import net. sf. hibernate. cfg. Configuration;
Import net. sf. hibernate. SessionFactory;
Import net. sf. hibernate. tool. hbm2ddl. SchemaExport;
Import net. sf. hibernate. Session;
Import net. sf. hibernate. Query;
Import net. sf. hibernate. Hibernate;
Import net. sf. hibernate. type. LongType;
Import net. sf. hibernate. Transaction;

/**
* @ Author getdown
* @ Version 1.0
*/

Public class Hello {
Public Hello (){
}

Public static void main (String [] args) throws Exception {
Configuration cfg = new Configuration (). addClass (Message. class );

/** As the name implies, create a table... Run the following statement at the first run to generate a table in the database.
* You can remove the following sentence.
**/
// New SchemaExport (cfg). create (true, true );

// Mr. sessionFactory
SessionFactory sessions = cfg. buildSessionFactory ();
// Obtain a session from sessionFactory
Session session = sessions. openSession ();
// Start database operations

/* ---- Create a database --------*/
Message message = new Message ("helloWorld ");
// Create a record
Session. save (message );
// Save the record
Session. flush ();

/* --- Query the database ---------------*/
// Message message = new Message ();
// Query q = session. createQuery ("from Message as message where message. id = 1 ");
// Message = (Message) q. list (). get (0 );
// Message. getNextMessage (). setText ("helloNext ");
// Session. flush ();
// Session. close ();
// Long id = new Long (1 );
// Message = (Message) Session. Find ("from message as message where message. ID =? ", ID, hibernate. Long). Get (0 );
// System. Out. println (message. gettext ());

/// * ------- Transaction processing ----------------*/
// Transaction Tx = session. begintransaction ();
// Try {
// Message = new message ("hello ");
// Session. Save (Message );
// Session. Flush ();
// Message = new message ("hello ");
// Session. Save (Message );
// Session. Flush ();
// Tx. Commit ();
//}
// Catch (hibernateexception ex ){
// Tx. rollback ();
//}

/* ------- Add 1000 records --------------*/
// Message;
// Long start = system. currenttimemillis ();
// For (int I = 0; I <1000; I ++ ){
// Message = new Message ("hello ");
// Session. save (message );
// Session. flush ();
//}
// Long end = System. currentTimeMillis ();
// System. out. println ("add 1000 record time ---" + (end-start)/1000 + "s ");

Session. close ();

}

}

Okay. Run it. Hello, let's see what it is.
Compared with the persistence of CMP persistent hibernate, it is not very lightweight ..
You can also try to see the performance of hibernate by removing the last comment of Hello. java from running it.

Of course, the most important thing about hibernate is its principle. There are still many good and interesting functions and O/RM design ideas waiting for you to explore.
Take a look at its own documents and learn a lot. Its documents are really good.

I recently joined hibernate and learned together with all hibernate learners.
Msn: java_xml@msn.com

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.