侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

Hibernate(3)之事务与查询

zze
zze
2017-07-14 / 0 评论 / 0 点赞 / 386 阅读 / 6735 字

事务

回顾

参考【数据库事务了解一下】。

事务的隔离级别

使用 Hibernate 也可以设置事务的隔离级别,只需要在核心配置文件 hibernate.cfg.xml 中添加如下属性即可:

<!--
配置事务隔离级别,有如下四个值:
:读未提交 (Read uncommitted)
:读已提交 (Read committed)
:可重复读 (Repeatable read) 默认级别
:串行化 (Serializable)
-->
<property name="hibernate.connection.isolation">4</property>

绑定 Session 到当前线程

在核心配置文件 hibernate.cfg.xml 中添加如下属性:

<!--
thread : Session 对象的生命周期与本地线程绑定。
jta : Session 对象的生命周期与 JTA 事务绑定。
managed : Hibernate 委托程序来管理 Session 对象的生命周期。
-->
<property name="hibernate.current_session_context_class">thread</property>

然后就可以保证在当前线程中任意一个地方通过 org.hibernate.SessionFactory.getCurrentSession 方法获取到的 session 是同一个实例。可抽取工具类:

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

public class HibernateUtil {
    public static final Configuration cfg;
    public static final SessionFactory sf;

    static {
        cfg = new Configuration().configure();
        sf = cfg.buildSessionFactory();
    }

    public static Session openSession() {
        return sf.openSession();
    }

    public static Session getCurrentSession() {
        return sf.getCurrentSession();
    }
}

Hibernate 内部是通过 ThreadLocal 来实现线程绑定 Session 的。

查询

Hibernate 为我们提供了如下几种查询方式。

HQL

HQL (Hibernate Query Language) ,相对 SQL 来说,SQL 中的表名在 HQL 中用类名替代,SQL 中的列名在 HQL 中用属性名替代。

简单查询

Session currentSession = HibernateUtil.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
String hql = "from Customer"; // 简单查询
Query query = currentSession.createQuery(hql);
List<Customer> customerList = query.list();
for (Customer customer : customerList) {
    System.out.println(customer);
}
transaction.commit();

条件查询

Session currentSession = HibernateUtil.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
String hql = "from Customer where cust_name like ?";
Query query = currentSession.createQuery(hql);
query.setParameter(0, "张%");
List<Customer> customerList = query.list();
for (Customer customer : customerList) {
    System.out.println(customer);
}
transaction.commit();

分页查询

Session currentSession = HibernateUtil.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
String hql = "from Customer";
Query query = currentSession.createQuery(hql);
query.setFirstResult(2); // 起始索引,从 0 开始
query.setMaxResults(2); // 每页条数
List<Customer> customerList = query.list();
for (Customer customer : customerList) {
    System.out.println(customer);
}
transaction.commit();

QBC

QBC (Query By Criteria) API 提供了检索对象的另一种方式,它主要由 Criteria 接口、Criterion 接口和 Expresson 类组成,它支持在运行时动态生成查询语句,是一种更面向对象的查询方式。

简单查询

Session currentSession = HibernateUtil.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
Criteria criteria = currentSession.createCriteria(Customer.class);
List<Customer> customerList = criteria.list();
for (Customer customer : customerList) {
    System.out.println(customer);
}
transaction.commit();

条件查询

Session currentSession = HibernateUtil.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
Criteria criteria = currentSession.createCriteria(Customer.class);
criteria.add(Restrictions.like("cust_name", "张", MatchMode.END));
List<Customer> customerList = criteria.list();
for (Customer customer : customerList) {
    System.out.println(customer);
}
transaction.commit();

分页查询

Session currentSession = HibernateUtil.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
Criteria criteria = currentSession.createCriteria(Customer.class);
criteria.setFirstResult(2);
criteria.setMaxResults(2);
List<Customer> customerList = criteria.list();
for (Customer customer : customerList) {
    System.out.println(customer);
}
transaction.commit();

SQL

Hibernate 也支持我们直接使用原生 SQL 进行查询。

简单查询:返回 List<Object[]>

Session currentSession = HibernateUtil.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
SQLQuery sqlQuery = currentSession.createSQLQuery("select * from customer");
// 默认返回一个 Object 数组对象的列表,数组的每一项对应数据库中每一行数据的一列
List<Object[]> customerList = sqlQuery.list();
for (Object[] customer : customerList) {
    System.out.println(String.format("id:%s,cust_name:%s", customer[0], customer[1]));
}
transaction.commit();

条件查询:返回 List<持久化类>

Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();
String sql = "select * from customer where cust_name like ?";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity(Customer.class);
sqlQuery.setParameter(0,"张%");
List<Customer> customerList = sqlQuery.list();
for (Customer customer : customerList) {
    System.out.println(customer);
}
session.getTransaction().commit();

简单查询:返回List<指定类型>

Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();
String sql = "select cust_id id,cust_name name from customer";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addScalar("id", new LongType());
sqlQuery.addScalar("name");
sqlQuery.setResultTransformer(Transformers.aliasToBean(Customer2.class));
List<Customer2> userList = (List<Customer2>)sqlQuery.list();
for (Customer2 customer2 : userList) {
    System.out.println(customer2);
}
session.getTransaction().commit();
0

评论区