如何获取JPA生成的SQL查询? [英] How to get the JPA generated SQL query?

查看:977
本文介绍了如何获取JPA生成的SQL查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JPA规范并将Hibernate作为我的供应商.我需要以某种方式将生成的SQL查询发送到数据库(打印到sysout)并将其保存为简单字符串.

I use JPA specification and Hibernate as my vendor. I need somehow to take the generated SQL Query which is sent to the the DB (printed to the sysout) and save it as a simple string.

有没有办法做到这一点?

Is there a way to do this?

编辑

让我更清楚一点:我不需要休眠日志.我需要能够在不同的数据库上执行相同的查询.因此,我需要按原样获取SQL查询,并将其保存在普通的String变量中.

Let me make it a beat clearer: I don't need hibernate log. I need to be able to execute the same query on a different DB. Therefore, I need to get the SQL query as is, and hold it in a normal String variable.

编辑2

是否有一个可以为它提供bean的实用程序,它将自动生成一个Insert查询?我可以在这里以某种方式使用休眠豆吗?我知道这是一个复杂的节奏.

Is there a util which I can provide it a bean and it will automatically generate an Insert query? can I somehow use Hibernate beans here? I know it's a beat complex.

谢谢

偶像

推荐答案

创建一个像这样的bean.

Create a bean like this.

@Bean
public JpaVendorAdapter jpaVendorAdapter(){
    HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
    jpaVendorAdapter.setGenerateDdl(true);
    jpaVendorAdapter.setShowSql(true);

    return jpaVendorAdapter;
}

如果您使用的是Spring Boot,请将其添加到您的@Configuration中.

If you're using Spring Boot add it somewhere to your @Configuration.

由此创建的日志可在MySQL工作台中执行. 您说您正在使用JPA和Hibernate.除了JPA支持您支持的数据库之外,没有其他方法.在这种情况下,您可以实现一个AbstractJpaVendorAdapter.

The logs created from this are executable in MySQL workbench. You stated that you are using JPA and Hibernate. There's no other way except if the database you support are supported by JPA. In that case there is an AbstractJpaVendorAdapter that you can implement.

这篇关于如何获取JPA生成的SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆