Simple Hibernate Access Database Demo, hibernate access data

Source: Internet
Author: User

Simple Hibernate Access Database Demo, hibernate access data

Recently I am studying SSH. Now I have seen Hibernate and implemented a simple Demo. I have a preliminary understanding of the functions and usage of Hibernate.

1. Copy the Hibernate jar package to the lib directory of the Web project. Some Dependent jar packages require additional import; for example, cglib-nodep.jar, otherwise an error will be reported.

2. Configure the object class. Here I use a simple Account class. Note that the annotation below javax. persistense. * is not under org. hibernate.

Package com. jobhelp. domain; import javax. persistence. column; import javax. persistence. entity; import javax. persistence. generatedValue; import javax. persistence. generationType; import javax. persistence. id; import javax. persistence. table; @ Entity // @ Entity indicates that the class can be persisted by hibernate @ Table (name = "user ") // The public class Account {@ Id of the data table corresponding to the specified Entity // specify the primary key @ GeneratedValue (strategy = GenerationType. AUTO) // auto indicates the AUTO-increment private Integer id; @ Column (name = "name") private String username; @ Column (name = "password") private String password; public int getId () {return id;} public void setId (int id) {this. id = id;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password ;}}

3. Create the Hibernate configuration file hibernate. cfg. xml in the src directory. (The MyEclipse wizard is automatically generated. If I use Eclipse, I have to create it myself .)

The content of hibernate. cfg. xml is as follows:

<? 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"> 

4. Create a New Hibernate tool class for obtaining sessions. Each session in Hibernate represents a complete database operation.

HibernateUtil. java officially provided by Hibernate

Package com. jobhelp. util; import org. hibernate. sessionFactory; import org. hibernate. cfg. annotationConfiguration; public class HibernateUtil {private static final SessionFactory sessionFactory; // SessionFactory in singleton mode // static code block. hibernate is initialized when the class is loaded, single Instance only initializes static {try {// from hibernate. cfg. the object class for loading Configuration // loading @ annotation Configuration in xml uses AnnotationConfiguration () // to load the object class of xml Configuration using Configuration () sessionFactory = new AnnotationConfiguration (). configure ("hibernate. cfg. xml "). buildSessionFactory ();} catch (Throwable ex) {System. err. println ("Initial SessionFactory Error"); throw new ExceptionInInitializerError (ex) ;}} public static SessionFactory getSessionFactory () {return sessionFactory ;}}

5. initialize the MySql database and create a simple User table. The table data I use is as follows.

mysql> select * from user;+----+-------+----------+| id | name  | password |+----+-------+----------+|  1 | admin | 123456   ||  2 | bowen | 123456   ||  3 | tom   | 123456   ||  4 | jack  | 123456   |+----+-------+----------+

6. Execute the hibernate program. Hibernate is An ORM framework that deals with databases.

The session process in Hibernate is similar to that in JDBC database operations.

Compared with the use of jdbcTemplate in Spring, hibernate does not need to write SQL statements, and does not need to encapsulate results. The logic is clear and the code is much simpler, which obviously improves the development efficiency.

The following is the code of the Hibernate Program executed in a Test class.

package com.jobhelp.util;import java.util.List;import org.hibernate.Session;import org.hibernate.Transaction;import com.jobhelp.domain.Account;public class Test {public static void main(String[] agrs){/*Account account =new Account();account.setUsername("jack");account.setPassword("123456");*///start a hibernate sessionSession session = HibernateUtil.getSessionFactory().openSession();//start a transactionTransaction transaction = session.beginTransaction();//insert into database//session.persist(account);@SuppressWarnings("all")//hql queryList<Account> list =session.createQuery("from Account").list();//print query resultfor(Account account2: list){System.out.println(account2.getId()+" : "+account2.getUsername());}transaction.commit();session.close();}}
Execution result:

[2014-11-24 21:26:19,083][DEBUG][org.hibernate.jdbc.AbstractBatcher:366] - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)[2014-11-24 21:26:19,083][DEBUG][org.hibernate.SQL:401] - select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_Hibernate: select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_......[2014-11-24 21:26:19,108][DEBUG][org.hibernate.engine.StatefulPersistenceContext:787] - initializing non-lazy collections1 : admin2 : bowen3 : tom4 : jack[2014-11-24 21:26:19,109][DEBUG][org.hibernate.transaction.JDBCTransaction:103] - commit......

Note: Hibernate only generates table structures, but does not create databases. If the specified database does not exist, hibernate will throw an exception.


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.