How to get the JPA generated SQL query?

前端 未结 6 1192
北荒
北荒 2020-12-28 17:50

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 simpl

相关标签:
6条回答
  • 2020-12-28 18:07

    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.

    0 讨论(0)
  • 2020-12-28 18:07

    I don't know what you mean by a generated query but if you use Hibernate and you have javax.persistence.Query query you can get HQL string very easy (for EclipseLink it is similar). And if you have HQL you can translete it to SQL with QueryTranslator.

    // Get HQL
    String hqlQueryString = query.unwrap(org.hibernate.query.Query.class).getQueryString();
    
    // Translate HQL to SQL
    ASTQueryTranslatorFactory queryTranslatorFactory = new ASTQueryTranslatorFactory();
    SessionImplementor hibernateSession = em.unwrap(SessionImplementor.class);
    QueryTranslator queryTranslator = queryTranslatorFactory.createQueryTranslator("", hqlQueryString, Collections.emptyMap(), hibernateSession.getFactory(), null);
    queryTranslator.compile(Collections.emptyMap(), false);
    String sqlQueryString = queryTranslator.getSQLString();
    
    0 讨论(0)
  • 2020-12-28 18:12

    The simple answer to your question is No. What you want to do is something that many developers would also like to do however it was not part of the JPA specification and thus the ability to get the generated SQL will depend upon what the vendor decided to do. Using Hibernate the only way to obtain the SQL is via the log.

    0 讨论(0)
  • 2020-12-28 18:12

    If I understand you correctly, you want to get the insert query which Hibernate is executed on one database, and via code, run it on a different database via entityManager#executeUpdate or similar.

    Hibernate does not expose the generated query as it is specific for the dialect of target database. So even if were to get the insert query, it could be pointless.

    However in your case, you can create two database connections (via two DataSource or EntityManagerFactory whatever in your case) and call dao.persist(entity) two times for both databases, and let Hibernate handle the query construction part.

    Edit: By query I mean native query here, HQL query would be same for both databases. Hope it helps.

    0 讨论(0)
  • 2020-12-28 18:20

    Try to add properties in instance of LocalContainerEntityManagerFactoryBean ,Its working for me :-

    @EnableJpaRepositories(basePackages = "org.common.persistence.dao")
    public class PersistenceJPAConfig {
    
        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
            final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
            em.setDataSource(dataSource());
            em.setPackagesToScan(new String[] { "org.common.persistence.model" });
            final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
            em.setJpaVendorAdapter(vendorAdapter);
            em.setJpaProperties(additionalProperties());
            return em;
        }
    
        final Properties additionalProperties() {
            final Properties hibernateProperties = new Properties();
            hibernateProperties.setProperty("showSql", "true");
            hibernateProperties.setProperty("hibernate.show_sql", "true");
            hibernateProperties.setProperty("hibernate.format_sql", "true");
            hibernateProperties.setProperty("hibernate.query.substitutions", "false");
            return hibernateProperties;
        }
    }
    
    0 讨论(0)
  • 2020-12-28 18:21

    You have to enable the log4j logging and add an appender for Hibernate to show the queries.

    This has already been described here: How to print a query string with parameter values when using Hibernate

    0 讨论(0)
提交回复
热议问题