簡單的Hibernate訪問資料庫Demo,hibernate訪問資料

來源:互聯網
上載者:User

簡單的Hibernate訪問資料庫Demo,hibernate訪問資料

最近在學習SSH,現在看到Hibernate這塊,動手實現了一個簡單的Demo,對Hibernate的功能、使用有了初步瞭解。

1、首先將Hibernate的jar包複製到Web項目的lib目錄下。有些依賴jar包,要額外匯入;比如cglib-nodep.jar,不然會報錯。

2、配置實體類。這裡我用的是一個簡單Account類,要注意使用的是javax.persistense.*下面的註解,不是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表示該類能被hibernate持久化@Table(name="user")//指定Entity對應的資料表名public class Account {@Id//指定該列為主鍵@GeneratedValue(strategy=GenerationType.AUTO)//auto為自增長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、在src目錄下建立Hibernate的設定檔hibernate.cfg.xml。(MyEclipse嚮導會自動產生,我用的是Eclipse,就得自己建立了。)

hibernate.cfg.xml的內容如下:

<?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"><hibernate-configuration><!--表明以下的配置是針對session-factory配置的,SessionFactory是Hibernate中的一個類,這個類主要負責儲存HIbernate的配置資訊,以及對Session的操作 --><session-factory><!--設定資料庫的驅動程式,Hibernate在串連資料庫時,需要用到資料庫的驅動程式 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property><!--設定資料庫的串連url:jdbc:mysql://localhost/hibernate,其中localhost表示mysql伺服器名稱,此處為本機, hibernate是資料庫名 --><property name="hibernate.connection.url">jdbc:mysql://localhost/User</property><!--串連資料庫是使用者名稱 --><property name="hibernate.connection.username">root </property><!--串連資料庫是密碼 --><property name="hibernate.connection.password">123456 </property><!--資料庫連接池的大小 --><property name="hibernate.connection.pool.size">20 </property><!--是否在後台顯示Hibernate用到的SQL語句,開發時設定為true,便於差錯,程式運行時可以在Eclipse的控制台顯示Hibernate的執行Sql語句。項目部署後可以設定為false,提高運行效率 --><property name="hibernate.show_sql">true </property><!--jdbc.fetch_size是指Hibernate每次從資料庫中取出並放到JDBC的Statement中的記錄條數。Fetch Size設的越大,讀資料庫的次數越少,速度越快,Fetch Size越小,讀資料庫的次數越多,速度越慢 --><property name="jdbc.fetch_size">50 </property><!--jdbc.batch_size是指Hibernate批量插入,刪除和更新時每次操作的記錄數。Batch Size越大,大量操作的向資料庫發送Sql的次數越少,速度就越快,同樣耗用記憶體就越大 --><property name="jdbc.batch_size">23 </property><!--jdbc.use_scrollable_resultset是否允許Hibernate用JDBC的可滾動的結果集。對分頁的結果集。對分頁時的設定非常有協助 --><property name="jdbc.use_scrollable_resultset">false </property><!--connection.useUnicode串連資料庫時是否使用Unicode編碼 --><property name="Connection.useUnicode">true </property><!--connection.characterEncoding串連資料庫時資料的傳輸字元集編碼方式,最好設定為gbk,用gb2312有的字元不全 --><!--  <property name="connection.characterEncoding">gbk </property>--><!--hibernate.dialect 只是Hibernate使用的資料庫方言,就是要用Hibernate串連那種類型的資料庫伺服器。 --><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect </property><!--指定對應檔為“hibernate/ch1/UserInfo.hbm.xml” --><!-- <mapping resource="org/mxg/UserInfo.hbm.xml"> --><mapping class="com.jobhelp.domain.Account"></mapping></session-factory></hibernate-configuration>

4、建立Hibernate工具類,用於擷取session。Hibernate中每一個session代表一次完整的資料庫操作。

Hibernate官方提供的HibernateUtil.java

package com.jobhelp.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;public class HibernateUtil {private static final SessionFactory sessionFactory;//單例模式的SessionFactory//static代碼塊,類載入時初始化hibernate,單例只初始化一次static{try{//從hibernate.cfg.xml中載入配置//載入@註解配置的實體類用AnnotationConfiguration()//載入xml配置的實體類使用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、初始化MySql資料庫,建一個簡單的User表即可,我用的表資料如下。

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

6、執行hibernate程式。Hibernate是ORM架構,與資料庫打交道。

Hibernate中session會話與JDBC操作資料庫流程差不多。

相對Spring中jdbcTemplate的使用,hibernate不用寫sql語句,不用封裝結果;邏輯清晰,代碼簡潔很多,顯然有利於提高開發效率。

下面是在一個Test類中,執行了Hibernate程式的代碼。

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();}}
執行結果:

[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......

注意:Hibernate只會產生表結構,但不會建立資料庫。如果指定資料庫不存在,hibernate會拋出異常。


相關文章

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.