Hibernate introduction and Getting Started case

Source: Internet
Author: User

In 3,000, a sword was a million-dollar division.

If you have not learned the three big SSH frameworks before, then you must have been using JDBC to manipulate the database. Now you can simply hand over the database interaction to hibernate.

Hibernate is an open source object-relational mapping framework that provides JDBC with a very lightweight object encapsulation that maps Pojo to database tables, is a fully automated ORM framework, and Hibernate automatically generates SQL statements, automatically executes, So that Java programmers can use object programming thinking to manipulate the database at will. Hibernate can be applied to any JDBC application, both in Java client applications and in servlet/jsp Web applications, and most revolutionary of all, hibernate can replace CMP in the EE architecture of the EJB application. The task of achieving data persistence.

Hibernate is an ORM framework for persistent layers. (Orm:object relational Mapping. Object Relational Mappings. The language of development is Java, object-oriented. The database used is a relational database (relational). is to create a mapping between the object and the table in the database, and manipulate the object to manipulate the table. )

After learning about hibernate, are you looking forward to it? OK, let's do a hibernate starter case.

First step: Download the Hibernate development package.: https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/

Step two: After the download is complete and unzipped you can see the following directory:

Step three: Next, enter Eclipse to create the Web project, and introduce the necessary jar packages, jar packages in the lib/required directory above

At the same time, database driver packages and logging packages are required, and a full project jar package for an introductory case such as:

Fourth step: Then create the database and the table,

Build Library:

CREATE DATABASE Hibernate

Build table:

CREATE TABLE ' Cst_customer ' (

' cust_id ' bigint (+) not NULL auto_increment COMMENT ' customer number (primary key) ',

' Cust_name ' varchar (+) not NULL COMMENT ' customer name (company name) ',

' Cust_source ' varchar (+) DEFAULT NULL COMMENT ' Customer information source ',

' cust_industry ' varchar (+) DEFAULT NULL COMMENT ' customer industry ',

' Cust_level ' varchar (+) DEFAULT NULL COMMENT ' Customer level ',

' Cust_phone ' varchar (+) DEFAULT NULL COMMENT ' fixed phone ',

' Cust_mobile ' varchar (+) DEFAULT NULL COMMENT ' mobile phone ',

PRIMARY KEY (' cust_id ')

) Engine=innodb auto_increment=1 DEFAULT Charset=utf8;

Fifth step: Build the Entity class based on the database table and generate the Get and set methods

Public class Customer {

Private Long cust_id;

Private String Cust_name;

Private String Cust_source;

Private String Cust_industry;

Private String Cust_level;

Private String Cust_phone;

Private String Cust_mobile;

Generate the corresponding get and set methods

}

Sixth step: To create a map, a mapping file usually has a naming convention: the class name. Hbm.xml, the mapping file is placed in the same directory as the entity. Create a mapping file first introduce the constraint, this code does not have to write, to the location of the copy come:

Open the Java resources/libraries/web App Libraries

Open Hibernate-core-5.0.7.final.jar/org.hibernate

Find and open hibernate-configuration-3.0.dtd at the bottom

Copy this paragraph as below

The following configuration looks at the diagram:

If there is no net at the time of writing the configuration file and there is no prompt, then the relevant files need to be configured:

When the last paragraph in the copy constraint is opened to the browser, a DTD file is automatically downloaded.

And then found in eclipse preferences such as: key is the last paragraph of the constraint, location is the path of the DTD file you just downloaded, configured after the case without a network will be prompted, if not yet restart.

Seventh step: Create the Hibernate core configuration file in the SRC directory:

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

<! DOCTYPE hibernate-configuration Public

"-//hibernate/hibernate Configuration DTD 3.0//en"

"Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >

<session-factory>

<!--information about connecting to the database--

<property name="Hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="Hibernate.connection.url">jdbc:mysql:///hibernate</property>

<!--Configure the user name and password for the connected database--

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

<property name="Hibernate.connection.password">123</property>

<!--database dialect: Generate different SQL--based on the underlying database

<property name="Hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!--configuration shows SQL--

<property name="Hibernate.show_sql">true</property>

<!--Configure formatted SQL--

<property name="Hibernate.format_sql">true</property>

<!--configuration Hbm2ddl

Hibernate.hbm2ddl.auto has several values

* None: Do not use mappings to go to DDL.

* Create: If the original table is deleted from the original table. A new table is created each time. used when testing.

* Create-drop: If there is a table to delete the original table. A new table is created each time. After performing the operation, the table is deleted. used when testing.

* Update: If there is a table in the database using the original table. If there is no table, a table is created. You can also update the existing table structure.

* Validate: The table is not created. Verify that the mapping and table structure are correct

-

<property name="Hibernate.hbm2ddl.auto">update</property>

<!--load a mapping file--

<mapping resource="Com/hibernate/domain/customer.hbm.xml"/>

</session-factory>

Eighth step: Writing test methods

Public class HibernateDemo1 {

@Test

/**

* Save operation

*/

Public void demo1 () {

Load Hibernate 's core configuration file.

Configuration configuration = new configuration (). Configure ();

Creates an Sessionfactory object.

Sessionfactory sessionfactory = Configuration.buildsessionfactory ();

Create session (equivalent to connection in JDBC)

Session session = Sessionfactory.opensession ();

To open a transaction:

Transaction Transaction = Session.begintransaction ();

Complete the operation:

Customer customer = new customer ();

Customer.setcust_name ("xxx");

Methods of saving

Session.save (customer);

Commit a transaction

Transaction.commit ();

Freeing resources

Session.close ();

}

}

Execute the method, you can add records in the database ....

So far, you've started hibernate. Come on. Tomorrow will be better.

Hibernate introduction and Getting Started case

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.