One of the powerful things about Hibernate is that you do not typically need to manually write SQL: you build a domain model that represents your data model in an object-oriented manner and then interact with your domain model. This is the ideal, but sometimes
you need to model a legacy data model or a data model that is not object-oriented in nature, which leads to either complicated Hibernate mappings or the inclusion of manual SQL. When this occurs, you do not want to have to build separate data access object
classes but rather you would like to find a way to seamlessly integrate SQL into your existing data access object classes in a way that your consumers do not even realize that you're not using Hibernate Query Language (HQL) under-the-hood.

Fortunately you do not need to jump through too many hoops to integrate manual JDBC into your Hibernate classes, you just need to perform the following steps:

  1. Obtain access to your Hibernate's Session object
  2. Create a class that implements org.hibernate.jdbc.Work, or create an anonymous inner class that implements the Work interface, and implement the execute() method
    using the supplied Connection object to execute your SQL
  3. Pass the Work class to Hibernate's doWork() method, which in turn invokes your Work's execute() method

Listings 1 and 2 illustrate how to use the Work interface to execute a simple SQL statement.

Listing 1. MyDao.java

...
public class MyDao
{
...
public String getValue( long id )
{
// Create a SQL order of work, which we will use to execute a manual SQL statement
MyWork myWork = new MyWork( id ); // Gain access to the underlying Hibernate session
Session session = getSessionFactory().openSession(); // Ask the Hibernate session to execute the unit of work
session.doWork( myWork ); // Obtain the results of the unit of work
return myWork.getValue();
}
..
}

Listing 1 defines a getValue() method that accepts an id and returns a String. It creates a newMyWork instance, passing it the id as an initialization parameter, locates a Hibernate Session, and
passes the MyWork instance to the Sessions doWork() method. After the query is complete, it retrieves the value from the MyWork class.

The mechanism that you use to obtain a Hibernate Session will be dependent on the technology with which you are building your data access object. If you're using Spring by extendingHibernateDaoSupport, you can invoke getSessionFactory().openSession() to
create a new Session object.

Listing 2 shows the source code for the MyWork class.

Listing 2. MyWork.java

public class MyWork implements Work
{
private long id;
private String value; public MyWork( long id )
{
this.id = id;
} public String getValue()
{
return value;
} @Override
public void execute( Connection connection ) throws SQLException
{
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = connection.prepareStatement( "SELECT * FROM table WHERE id = ?" );
ps.setLong( 1, id );
rs = ps.executeQuery();
while( rs.next() )
{
value = rs.getString( 1 );
}
}
catch( SQLException e ) { }
finally {
if( rs != null )
{
try {
rs.close();
}
catch( Exception e ) {}
}
if( ps != null )
{
try {
ps.close();
}
catch( Exception e ) {}
}
}
}
}

The MyWork class implements its data access logic in its execute() method. The execute() method is passed a java.sql.Connection object that you can use as you normally
would to create aStatementPreparedStatement, or CallableStatement. The doWork() method returns void, so it is up to you to develop
a mechanism to return a value from your unit of work.

If you are executing SQL from which you do not necessarily need to retrieve results, you can accomplish the same results by creating an anonymous inner class:

       // Gain access to the underlying Hibernate session
Session session = getSessionFactory().openSession(); // Ask the Hibernate session to execute the unit of work
session.doWork( new Work() {
@Override
public void execute( Connection connection ) {
// Implement your SQL here
}
} );

In this example we create the Work() implementation in the doWork() method invocation and override the execute() method. Depending on your background this might look a bit strange, but once you get used to it, this is a fairly elegant way to implement your
solution because it reduces the number of explicit classes you need to create and it couples the logic being executed with the invocation of that logic. For complicated cases you want to loosely couple things, but for a SQL statement it is overkill to create
additional classes if you do not need to. The challenge here, however, is that if you need to obtain results from the query, you're limited because the doWork()method returns void.

Hibernate offers a simple mechanism to execute SQL inside your Hibernate data access object classes by defining a unit of work and passing it to your Hibernate Session's doWork() method. You can define your unit of work explicitly
by creating a class that implements org.hibernate.jdbc.Workor by creating an anonymous inner class that implements the Work interface on-the-fly. The best solution, if you are building your domain
model from scratch, is to model your objects as simply as you can (remember the KISS principle: keep it simple, stupid), but if you have to create a domain model that does not lend itself easily to an object-oriented representation then you can integrate manual
SQL in this manner.

Integrating JDBC with Hibernate的更多相关文章

  1. 【JAVA - SSM】之MyBatis与原生JDBC、Hibernate访问数据库的比较

    首先来看一下原生JDBC访问数据库的代码: public static void main(String[] args) { // 数据库连接 Connection connection = null ...

  2. JDBC、Hibernate、Mybaites处理数据的流程及对DAO的理解

    以查询一个用户信息(id,name)为例: JDBC 1. 获取一个connection 2. 生成一个statement 3. 拼接SQL语句 4. 查询对象,获取结果集(假设已经找到我们需要的对象 ...

  3. 从JDBC到hibernate再到mybatis之路

    一.传统的JDBC编程 在java开发中,以前都是通过JDBC(Java Data Base Connectivity)与数据库打交道的,至少在ORM(Object Relational Mappin ...

  4. jdbc,mybatis,hibernate各自优缺点及区别

    先比较下jdbc编程和hibernate编程各自的优缺点.    JDBC:    我们平时使用jdbc进行编程,大致需要下面几个步骤:    1,使用jdbc编程需要连接数据库,注册驱动和数据库信息 ...

  5. jdbc 和 hibernate 比较

    相同点:都是数据库操作的中间件,都不是线程安全需要即时关闭,都可以对数据库操作进行显式处理. 不同:jdbc使用标准sql语言,hibernate使用HQL,操作对象jdbc直接操作数据传送到数据库, ...

  6. 【JavaEE】之MyBatis与原生JDBC、Hibernate访问数据库的比较

    首先来看一下原生JDBC访问数据库的代码: public static void main(String[] args) { // 数据库连接 Connection connection = null ...

  7. JDBC与Hibernate的区别

    相同点: ◆两者都是JAVA的数据库操作中间件. ◆两者对于数据库进行直接操作的对象都不是线程安全的,都需要及时关闭. ◆两者都可以对数据库的更新操作进行显式的事务处理. 不同点: ◆使用的SQL语言 ...

  8. 详解JDBC与Hibernate区别

    详解JDBC与Hibernate区别 引用地址:http://www.cnblogs.com/JemBai/archive/2011/04/13/2014940.html 刚开始学习JAVA时,认为H ...

  9. JDBC vs Hibernate(转)

    jdbc和Hibernate区别 刚开始学习JAVA时,认为Hibernate是一个很神圣的东西,好像是会了SSH,就能走遍全世界一样.记得曾经在枫叶面试的时候,我们几个同学出还说这个公司怎么这么的落 ...

  10. 请说说你对Hibernat的理解?JDBC和Hibernate各有什么优势和劣势?

    Hibernate是一个轻量级的持久层开源框架,它是连接Java应用程序和关系数据库的中间件,负责Java对象和关系数据之间的映射.Hibernate内部对JDBC API进行了封装,负责Java对象 ...

随机推荐

  1. 【Azure Developer】上手 The Best AI Code "Cursor" : 仅仅7次对话,制作个人页面原型,效果让人惊叹!

    AI Code 时代早已开启,自己才行动.上手一试,让人惊叹.借助这感叹的情绪,把今天操作Cursor的步骤记录下来,也分享给大家. 推荐大家上手一试,让你改变! 准备阶段 下载 Cursor(htt ...

  2. 低代码 + BI 数字化转型如何助力制造业供应链协同?

    引言 在当今快速变化的商业环境中,制造业面临着前所未有的挑战和机遇.全球化竞争.消费者需求的快速变化.技术创新的加速以及不断增加的成本压力,都要求制造企业不断提高其供应链的效率和灵活性.供应链协同作为 ...

  3. CSP-S 2023

    T1 直接 \(10^{5}\) 枚举状态就过了,合法的非零差分数量只可能为 \(1,2\)(\(0\) 相当于没转,按照题意 "都不是正确密码" 是不符的) 需要注意的是形如 0 ...

  4. 树莓派2 CentOS7.9 安装配置笔记

    1. 镜像下载与安装 http://isoredirect.centos.org/altarch/7/isos/armhfp/找到https://mirrors.tuna.tsinghua.edu.c ...

  5. KSM的使用

    使能KSM KSM只会处理通过madvise系统调用显式指定的用户进程地址空间,因此用户程序想使用这个功能就必须在分配地址空间时显式地调用madvise(addr,length,MADV_MERGEA ...

  6. 分布式缓存 - 缓存服务器 - redis

    如果一般的缓存可以解决问题,就不必使用分布式缓存 : 一般使用分布式缓存 都是使用 redis : 使用教程: 1. 安装包 Microsoft.Extensions.Caching.StackExc ...

  7. 有没有开发过⼀些vue插件?举例说说 - 批量引入插件

    有过,项⽬开发的时间⻓了,沉淀了不少业务通⽤全局组件,想把他们统⼀进⾏注册,就封装了⼀个⼩ 插件 当时其实⼀开始也没有什么思路,后来扒了⼀下 elementUI的源码,仿了⼀下它的写法,流程我还⼤概记 ...

  8. 66.有没有碰到过数组响应丢失(问的是ref和reactive的用法,什么情况下用)

    由于vue3使用proxy,对于对象和数组都不能直接整个赋值.  直接赋值丢失了响应性 只有push或者根据索引遍历赋值才可以保留reactive数组的响应性  : 可以使用 toRefs 解决这个问 ...

  9. 云原生周刊:LitmusChaos 审计完成|2024.9.2

    开源项目推荐 Gardener Gardener 实现了 Kubernetes 集群的自动化管理和操作服务,并提供了一个经过完全验证的可扩展性框架,可以调整以适应任何编程云或基础设施提供商. Graf ...

  10. centos 安装mbstring(mb_strlen )

    部署onethink框架的时候,检测到mb_strlen未支持, 在网上检索一大堆教程,最多的就是先检测一下需要安装的安装包 yum search php 楼主小白满心欢喜地输入,一对照返回的结果, ...