jpa mysql sql查询,如何获取JPA生成的SQL查询?

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?

EDIT

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.

Edit 2

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.

Thanks,

Idob

解决方案

Create a bean like this.

@Bean

public JpaVendorAdapter jpaVendorAdapter(){

HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();

jpaVendorAdapter.setGenerateDdl(true);

jpaVendorAdapter.setShowSql(true);

return jpaVendorAdapter;

}

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

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.