Hibernate使用

Hibernate使用

  hibernate是一个ORM框架。

  ORM的全拼是Object Relational Mapping,译为“对象关系映射”,是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上来说,它其实是创建了一个可以在编程语言里使用的“虚拟对象数据库”。

  使用较多的ORM框架有:  

JPA---- Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系(只有接口规范)
Hibernate---- 最流行ORM框架,通过对象-关系映射配置,可以完全脱离底层SQL
MyBatis----  本是apache的一个开源项目 iBatis,支持普通 SQL查询,存储过程和高级映射的优秀持久层框架
Apache---- DBUtils 
Spring---- JDBCTemplate

  接下来,我们通过一个案例演示hibernate的使用。先在项目中导入hibernate所需的一系列jar包:

Hibernate使用_第1张图片

  接着,在源代码根路径下创建并配置hibernate.cfg.xml文件:





    
        jdbc:mysql://localhost:3306/b0307
        com.mysql.jdbc.Driver
        root
        2018
        true
        true
        org.hibernate.dialect.MySQLDialect
        thread
        
    

  然后,映射数据库中的一个表,并据此创建映射的类Emp,并配置该类基于hibernate的配置文件Emp.hbm.xml:

package com.itszt.domain;

/**
 * 测试用的实体类
 */
public class Emp {
    private int uid;
    private String name;

    public Emp(int uid, String name) {
        this.uid = uid;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "uid=" + uid +
                ", name='" + name + '\'' +
                '}';
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Emp() {
    }
}

  Emp.hbm.xml配置文件:





    
        
            
        
        
    
    
        SELECT new Emp(uid,name) FROM Emp WHERE uid=? order by uid desc
    
    
        FROM Emp order by uid desc
    
    
         ? and uid < ?
        ]]>
    

  测试类:

import com.itszt.domain.Emp;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * 测试类
 */
public class Test {
    public static void main(String[] args) {
        Configuration configuration=new Configuration().configure("hibernate.cfg.xml");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Emp emp = new Emp();
        emp.setUid(2);
        emp.setName("小马222");

        Transaction transaction = session.beginTransaction();
        //演示操作增删改查
//        session.save(emp);
//        session.delete(emp);
//        session.update(emp);
        Emp emp1 = (Emp) session.get(Emp.class, 2);
        System.out.println("emp1 = " + emp1);

        transaction.commit();

        session.close();
        sessionFactory.close();

    }
}

  此外,我们再创建一个工具类UtilHibernate,用来基于hibernate生成一个session:

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 工具类
 */
public class UtilHibernate {
    private static Configuration configuration;
    private static SessionFactory sessionFactory;

    //什么是要重复调用的
    //什么是要初始加载一次的
    static {
        try {
            configuration=new Configuration().configure();
            sessionFactory = configuration.buildSessionFactory();
            //JVM的关闭钩子,在JVM退出时close我们的sessionFactory
            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    super.run();
                    System.out.println("Execute Hook.....");
                    if (sessionFactory != null) {
                        sessionFactory.close();
                    }
                }
            });
        } catch (HibernateException e) {
           throw  new ExceptionInInitializerError("hibernate加载失败!!");
        }
    }

    public static Session openNew(){
       return sessionFactory.openSession();
    }

    public static Session getCurrent(){
        return sessionFactory.getCurrentSession();
    }

    public static void release(Session session){
        if (session != null) {
            if (session.isOpen()) {
                session.close();
            }
        }
    }
}

  接下来,通过该工具类,再分别通过query查询,hql,以及criteria来测试各自的用法:

TestQuery.java

import com.itszt.domain.Emp;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * 测试查询
 */
public class TestQuery {

    public static void main(String[] args) {
        Session session1 = UtilHibernate.getCurrent();
        Transaction transaction = session1.beginTransaction();
        //饿加载:只要查询,马上就执行sql然后把结果取回
        Emp emp1= (Emp) session1.get(Emp.class, 2);
        System.out.println("emp1 = " + emp1);
        transaction.commit();
        UtilHibernate.release(session1);

        Session session2 = UtilHibernate.getCurrent();
        Transaction transaction2 = session2.beginTransaction();
        //懒加载:等到使用该对象的时候再执行sql然后把结果取回
        Emp emp2= (Emp) session2.load(Emp.class, 2);
        System.out.println("emp2 = " + emp2);


        transaction2.commit();
        UtilHibernate.release(session2);

        //退出JVM。。。
        System.exit(0);

    }
}
-----------------------------------------------------
TestHQL.java

import com.itszt.domain.Emp;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.Arrays;
import java.util.List;

/**
 * HQL查询语言
 */
public class TestHQL {

    //:role形式的参数设置查询
    public static void main(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("SELECT new Emp(uid,name) FROM Emp WHERE uid=:uid AND name=:name");
//        query.setParameter("uid",8);
//        query.setParameter("name","测试角色2222222");

        Emp emp=new Emp(2,"小马222");
        query.setProperties(emp);

        Object result = query.uniqueResult();
        System.out.println("result = " + result);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }

    public static void main4(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("SELECT new Emp(uid,name) FROM Emp WHERE uid=?");
        query.setParameter(0,2);
        Emp emp= (Emp) query.uniqueResult();
        System.out.println("emp = " + emp);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }

    //查询其中的几列
    public static void main3(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("SELECT uid,name FROM Emp WHERE uid=?");
        query.setParameter(0,2);

        Object[] results= (Object[]) query.uniqueResult();
        System.out.println("results = " + Arrays.toString(results));

        Query query1 = session.createQuery("SELECT COUNT (*) FROM Emp");
        Long num = (Long) query1.uniqueResult();
        System.out.println("num = " + num);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }

    //查询单个数据,设置查询条件,返回单个对象
    public static void main2(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("FROM Emp WHERE uid=?");
        query.setParameter(0,2);
        Emp emp= (Emp) query.uniqueResult();
        System.out.println("emp = " + emp);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }

    //查询全部数据 ,返回一个list
    public static void main1(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("FROM Emp");
        List list = query.list();
        System.out.println("list = " + list);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }
}
--------------------------------------------
TestHQL2.java

import com.itszt.domain.Emp;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.Arrays;
import java.util.List;

/**
 * HQL查询语言2
 */
@SuppressWarnings("ALL")
public class TestHQL2 {

    //原生SQL查询
    public static void main(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM emp");
        sqlQuery.addEntity(Emp.class);
        List emp = (List) sqlQuery.list();
        System.out.println("emp = " + emp);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);

    }

    //原生SQL查询
    public static void main2(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM emp");
        List list = sqlQuery.list();
        for (Object[] o : list) {
            System.out.println("o = " + Arrays.toString(o));
        }
        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }

    //将SQL写在配置文件里
    public static void main1(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        Query query = session.getNamedQuery("queryTest1");
        query.setParameter(0,8);
        Emp emp= (Emp) query.uniqueResult();
        System.out.println("emp = " + emp);

        Query queryTest2 = session.getNamedQuery("queryTest2");
        List list = queryTest2.list();
        System.out.println("list = " + list);

        Query queryTest3 = session.getNamedQuery("queryTest3");
        queryTest3.setParameter(0,2);
        queryTest3.setParameter(1,6);
        List list2 = queryTest3.list();
        System.out.println("list2 = " + list2);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }

}
------------------------------------------------------
TestCriteria.java

import com.itszt.domain.Emp;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import java.util.List;

/**
 * 测试Criteria方式
 */
public class TestCriteria {

    public static void main(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        Criteria criteria = session.createCriteria(Emp.class);
        //基本比较
        //criteria.add(Restrictions.lt("uid",5));
//        criteria.add(Restrictions.lt("uid",3));
//        criteria.add(Restrictions.gt("uid",1));

        //分页---------
        criteria.setFirstResult(0);
        criteria.setMaxResults(5);
        //分页---------

        List emps= criteria.list();
        System.out.println("emps = " + emps);

        //聚合
        /*criteria.setProjection(Projections.sum("uid"));
        Long result= (Long) criteria.uniqueResult();
        System.out.println("result = " + result);*/

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }

    public static void main1(String[] args) {
        Session session = UtilHibernate.getCurrent();
        Transaction transaction = session.beginTransaction();

        Criteria criteria = session.createCriteria(Emp.class);
        criteria.add(Restrictions.eq("uid",6));
        Emp emp = (Emp) criteria.uniqueResult();
        System.out.println("emp = " + emp);

        transaction.commit();
        UtilHibernate.release(session);
        System.exit(0);
    }
} 

 

posted @ 2018-04-13 19:21 奔跑在梦想的道路上 阅读( ...) 评论( ...) 编辑 收藏

你可能感兴趣的:(Hibernate使用)