[Advanced path to SSH] hiberante3 Development Environment + simple instance (2)

Source: Internet
Author: User

Hibernate is a typical persistence layer framework. The persistence idea is worth learning and researching. In this blog post, we will learn about hibernate in the form of an instance, without going into the ideas and principles of hibernate. Otherwise, we will never learn anything at the end of the article by simply pursuing the hard work and principles, starting from practice, practice makes perfect, and naturally understands thoughts and principles.

In the previous blog: [the path to advanced SSH] basic principles of hibernate, we introduced the basic concepts of hibernate, the core of hibernate, and the Implementation Principles of hibernate, which can help us understand hibernate very well, before reading this blog, review the content of the previous blog. In this blog post, we will build a simple hibernate instance from the perspective of practice.


I. Development Environment


Win8 + jdk1.7 + myeclipse + tomcat5.0 + MySql

Note: In fact, Hibernate is a very independent framework and does not require myeclipse, Eclipse, tomcat, and log4j at all. They just bring them in to meet our other needs.


Ii. download files


You need Java SDK, Hibernate package, and JDBC driver.

1. hibernate package:
Http://prdownloads.sourceforge.net/hibernate? Sort_by = Date & sort = DESC

2. JDBC driver depends on your database, which is usually available on the official database website. Hibernate supports common databases, such as MySQL and Oracle. These two databases are currently commonly used and both have JDBC driver:

Oracle JDBC Driver (Oracle agreement must be agreed before download)
Http://otn.oracle.com/software/htdocs/distlic.html? /Software/Tech/Java/sqlj_jdbc/htdocs/jdbc9201.html

MySQL JDBC driver
Http://dev.mysql.com/downloads/connector/j/3.0.html

Iii. Required jar packages


Hibernate3.jarHibernate core package

Dom4j-1.6.1.jarDom4j reads XML file packages

Mysql-connector-java-3.1.13-bin.jarMySQL JDBC driver package

The role of hibernate: Let's consider how to access data from a relational database in an object-oriented way or by thinking. It needs to deal with the corresponding database, so the corresponding JDBC driver is required. Our database uses MySQL, so we need to introduce the MySQL JDBC driver.

Log4j-1.2.11.jarLogging framework

Because the logging function of log4j is more beautiful and simple than that of JDK, it is easy to configure the log level and facilitate debugging, we choose to use log4j.

Jar to be introduced:

Commons-logging-1.0.4.jarAbstract logging framework

It does not implement real log writing capabilities (you can see the package structure), but integrates with other log systems such as log4j or Java. util. logging is used as a log output component to implement the logging function.

Commons-collections-2.1.1jarEncapsulation of various collection classes and collection tool classes

Cglib-2.1.3.jarDynamic proxy. hibernate uses it to dynamically generate Po bytecode.

ASM. JarJar and ASM bytecode library that cglib depends on

Note: As a beginner, this method is not recommended. You only need to introduce the third-party jar packages that hibernate depends on. Otherwise, the noclassdeffounderror error will be reported when other instances are created. solution: you only need to introduce the corresponding jar. Because this is a simple instance, you only need to introduce these jar files.

4. Code display

1. Create a Java project in IDE (relatively simple and not demonstrated)

2. Create source folder and name it hibernate3. In the hibernate download file, find the three configuration files and all jar packages we need, copy the required jar files, and build the dependency packages.


3. Provide the hibernate. cfg. xml file to complete basic configuration.

4. write code

(1) Create entity class user. Java

package com.liang.hibernate;import java.util.Date;public class User {private String id;private String name;private String password;private Date createTime;private Date expireTime;public String getId() {return id;}public void setId(String id) {this.id = id;}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 Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}public Date getExpireTime() {return expireTime;}public void setExpireTime(Date expireTime) {this.expireTime = expireTime;}}

(2) provide the user. HBM. xml file to complete object class ing

<Span style = "font-size: 12px;"> <? XML version = "1.0"?> <! Doctype hibernate-mapping public "-// hibernate/hibernate DTD ing DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

(3) Add the user. HBM. xml file to the hibernate. cfg. xml file.

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

(4) Compile the tool class exportdb. Java to generate DDL for HBM, that is, hbm2ddl.

Package COM. liang. hibernate; import Org. hibernate. cfg. configuration; import Org. hibernate. tool. hbm2ddl. schemaexport;/*** generate DDL * @ author liang for HBM **/public class exportdb {public static void main (string [] ARGs) {// Hibernate is read by default. cfg. XML file configuration CFG = new configuration (). configure (); // generate and output the SQL statement to the file (current directory) and database schemaexport export = new schemaexport (CFG); export. create (True, true );}}

Before testing, you must create the database hibernate_first in advance. The test is as follows:

SQL statements printed on the console:

drop table if exists Usercreate table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime date, expireTime date, primary key (id))

Database table structure:

(5) create a client-class client and add user data to MySQL

Package COM. liang. hibernate; import Java. util. date; import Org. hibernate. session; import Org. hibernate. sessionfactory; import Org. hibernate. cfg. configuration; public class client {public static void main (string [] ARGs) {// read hibernate. cfg. XML file configuration CFG = new configuration (). configure (); // create sessionfactorysessionfactory = cfg. buildsessionfactory (); // get Sessionsession session = NULL; try {// enable ses Sionsession = factory. opensession (); // start the transaction session. begintransaction (); User user = new user (); User. setname ("jiuqiyuliang"); User. setpassword ("123456"); User. setcreatetime (new date (); User. setexpiretime (new date (); // Save the Session of the user object. save (User); // submit the transaction session. gettransaction (). commit ();} catch (exception e) {e. printstacktrace (); // roll back the transaction session. gettransaction (). rollback ();} finally {If (session! = NULL) {If (session. isopen () {// close Sessionsession. Close ();}}}}}


Right-click debug to run the test. After the test is completed, query the test result:

5. To observe the hibernate log output during debugging, it is best to add log4j. properties configuration file, create log4j in classpath. properties configuration file or copy the configuration file to SRC for program debugging.

The content is as follows:

<span style="font-size:12px;">### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=warn, stdout</span>

After the configuration is complete, the project structure is shown in:


V. Final

Do it yourself, practice the truth, and get a glimpse of it on the paper. Although this instance is very simple, we step into the door of the persistent layer framework.

From the simple example above, we can see that we only use hibernate to map the object "user", which is relatively simple but completely not realistic. We still need to know how to express multiple associations like relational databases, such as one-to-one, one-to-many, and many-to-many. In the next blog, we will introduce the basic ing principle and associated relationship ing of hibernate.

[Advanced path to SSH] hiberante3 Development Environment + simple instance (2)

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.