Hibernate第一个实例

1、Hibernate优点:

(1)简化开发,提高开发效率

底部封装数据库操作,使用起来更加简洁方便

(2)更加面向对象设计

只用关心按照面向对象的方法实现业务逻辑,不用关心数据库等创建于操作。

数据库:是关系数据库,是面向关系的。而java是面型对象的,所以需要ORM(对象关系映射)。而Hibernate直接封装好了之间的映射。

(3)更好的性能

Hibernate中使用hql语句进行数据操作,hql相对于sql语句效率稍微低一点,因为hql要生成sql语句进行数据库操作,而且sql还可以进行优化。但是生成的sql效率很高,比一般程序员写的语句可能更高,而且还设置的有缓存机制。两者决定着性能的高低。

(4)更好的移植性

底层数据库屏蔽,根据数据库的不同,进行转化。直接写hql语句就行,不用关系具体数据库操作。

2、ORM框架比较:

Hibernate学习(一)_第1张图片

 

3、JPA 全称:Java Persistence API(运行时把实体对象持久到数据库中)

HibernateSpringOpenJPAToplink等都是JPA的实现。(但是HIbernate早于JPA的实现)

JPAjavaee5.0的亮点。

 

SessionFactory一个应用只有一个,二级缓存,创建session对象。

一个session对象只有在一个线程中使用

4、初步学习(Hibernate第一个实例)

 

(1)加入包

Hibernate包和数据库连接:

Hibernate学习(一)_第2张图片

 

(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>  

<session-factory>

<property name="show_sql">trueproperty>

<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialectproperty>

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

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

        <property name="connection.username">rootproperty>  

        <property name="connection.password">abc123property>  

             

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

          

        <property name="current_session_context_class">threadproperty>  

  

          

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProviderproperty>  


          

        <property name="hbm2ddl.auto">updateproperty>  

        <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)

  

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

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

  

  

(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();

}

}

}