Hibernate學習(一)

Hibernate第一個實例

1、Hibernate優點:

(1)簡化開發,提高開發效率

底部封裝數據庫操作,使用起來更加簡潔方便

(2)更加面向對象設計

只用關心按照面向對象的方法實現業務邏輯,不用關心數據庫等創建於操作。

數據庫:是關係數據庫,是面向關係的。而java是面型對象的,所以需要ORM(對象關係映射)。而Hibernate直接封裝好了之間的映射。

(3)更好的性能

Hibernate中使用hql語句進行數據操作,hql相對於sql語句效率稍微低一點,因爲hql要生成sql語句進行數據庫操作,而且sql還可以進行優化。但是生成的sql效率很高,比一般程序員寫的語句可能更高,而且還設置的有緩存機制。兩者決定着性能的高低。

(4)更好的移植性

底層數據庫屏蔽,根據數據庫的不同,進行轉化。直接寫hql語句就行,不用關係具體數據庫操作。

2、ORM框架比較:

wKioL1aCRC-i7tbAAAFrc-bxDfA347.png

 

3、JPA 全稱:Java Persistence API(運行時把實體對象持久到數據庫中)

HibernateSpringOpenJPAToplink等都是JPA的實現。(但是HIbernate早於JPA的實現)

JPAjavaee5.0的亮點。

 

SessionFactory一個應用只有一個,二級緩存,創建session對象。

一個session對象只有在一個線程中使用

4、初步學習(Hibernate第一個實例)

 

(1)加入包

Hibernate包和數據庫連接:

wKioL1aCRC-jlGARAAA-T7JKKXE839.png

 

(2)建立Hibernate配置文件(hibernate.cfg.xml)

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

<!DOCTYPE hibernate-configuration PUBLIC  

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  

        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  

  

<hibernate-configuration>  

<!-- 從官方文檔hibernate.property中獲取(裏面有連接各種數據庫的實例) -->

<session-factory>

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

<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

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

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

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

        <property name="connection.password">abc123</property>  

           <!-- JDBC connection pool (use the built-in) -->  

        <property name="connection.pool_size">1</property>  

        <!-- Enable Hibernate's automatic session context management -->  

        <property name="current_session_context_class">thread</property>  

  

        <!-- Disable the second-level cache  -->  

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>  


        <!-- Drop and re-create the database schema on startup -->  

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

        <mapping resource="hibernate/test/xml/Student.hbm.xml"></mapping>

</session-factory>

</hibernate-configuration>

(3)建立實體類

package hibernate.test.domain;

public class Student {

private int id;

private String sNo;

private String name;

private String pass;

private String schoolName;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getsNo() {

return sNo;

}

public void setsNo(String sNo) {

this.sNo = sNo;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPass() {

return pass;

}

public void setPass(String pass) {

this.pass = pass;

}

public String getSchoolName() {

return schoolName;

}

public void setSchoolName(String schoolName) {

this.schoolName = schoolName;

}

public Student(String sNo, String name, String pass,

String schoolName) {

super();

this.sNo = sNo;

this.name = name;

this.pass = pass;

this.schoolName = schoolName;

}

public Student() {

super();

// TODO Auto-generated constructor stub

}

}

 

(4)建立對應實體類的映射文件(student.hbm.xml)

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

<!DOCTYPE hibernate-mapping PUBLIC  

        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  

        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  

  

<hibernate-mapping package="hibernate.test.domain">  

<class name="Student" table="student" lazy="true">

<id name="id">

<generator class="native"/>

</id>

<property name="sNo" column="sno" not-null="true"  type="java.lang.String"></property>

<property name="name" type="java.lang.String"></property>

<property name="pass" type="java.lang.String"></property>

<property name="schoolName" type="java.lang.String"></property>

</class>

</hibernate-mapping>

(5)測試類

public class Test1 {

public static void main(String[] args) throws SecurityException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException {

// TODO Auto-generated method stub

Configuration configuration=new Configuration();

configuration.configure();

SessionFactory sessionFactory=configuration.buildSessionFactory();

Session session=sessionFactory.openSession();

//必須加事務,要麼數據庫就沒有插入數據

Transaction transaction=session.beginTransaction();

Student student=new Student("201200834201","name","000000","zhongyuangongxueyaun1");

session.save(student);

transaction.commit();

session.close();

}

}

Hibernate事務默認是不提交的,增刪改都需要提交事務,查不需要提交事務

5、單例模式SessionFactory一個web應用中只有一個)

封裝session

package hibernate.test.test;

import org.hibernate.Session;

import org.hibernate.SessionFactory;  

import org.hibernate.cfg.Configuration;  

public class HibernateUtil {  

    private static SessionFactory sessionFactory;

    private HibernateUtil(){  

    }

    static{

    Configuration configuration=new Configuration();

    configuration.configure("hibernate.cfg.xml");

    sessionFactory=configuration.buildSessionFactory();

    }

    public static SessionFactory getSessionFactory(){

    return sessionFactory;

    }

    public static Session getSession(){

    return sessionFactory.openSession();

    } 

}  

 

Test2中調用session,向數據庫插入數據,測試如下:

package hibernate.test.test;

import hibernate.test.domain.Student;

import org.hibernate.Session;

import org.hibernate.Transaction;

public class Test2 {

public static void main(String[] args) {

// TODO Auto-generated method stub

Session session=null;

Transaction tx=null;

try {

session=HibernateUtil.getSession();

tx=session.beginTransaction();

Student student=new Student("201200834202","nameytt","000000","zhongyuangongxueyaun1");

session.save(student);

tx.commit();

} catch (Exception e) {

// TODO: handle exception

if(tx!=null)

{

tx.rollback();

}

throw e;

}

finally{

if(session!=null)

{session.close();}

}

}

}

插入成功!

6、Hibernate生命週期

見:http://www.cnblogs.com/wangchenyang/archive/2011/08/23/2150373.html

public static void main(String[] args) {

// TODO Auto-generated method stub

Session session=null;

Transaction tx=null;

try{

session=HibernateUtil.getSession();

tx=session.beginTransaction();

//通過反射機制去獲取對象

//如果id=2的記錄不存在,返回null。get方法是在緩存(session中 一級緩存)中進行查找,若無,再在sessionFactory(二級緩存)中進行查找,若無,再連接數據庫重新查找

Student student=(Student) session.get(Student.class, 2);

System.out.println(student.getName());

//如果id=2的記錄不存在,則會拋出異常,一般用於這個記錄一定存在的情況。該方法有懶加載。

//Student student2=(Student) session.load(Student.class, 2);

student.setName("ytt_01");

session.save(student);

System.out.println(student.getName());

tx.commit();

} catch (Exception e) {

// TODO: handle exception

if(tx!=null)

{

tx.rollback();

}

throw e;

}

finally{

if(session!=null)

{

session.close();

}

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章