Spring data JPA - Dynamic SQL Execution

巧了我就是萌 提交于 2021-01-29 09:17:00

问题


I want to Execute the SQL , which will be constructed completely at runtime and it can be querying any tables in the schema.

Something like

@Repository public interface BaseRepository extends JpaRepository<Object, Integer> {        
    @Query(":dynamicSQL")   
    List<Object> dynamicExecution(@Param("dynamicSQL") String dynamicSQL);           
}

Please suggest how this can be implemented


回答1:


JpaRepository is not designed to be used like this. If you want to execute dynamic SQL query then use EntityManager. This is bad design but if you still want to do this then use default methods and pass a EntityManager bean like this:

default List<?> dynamicExecution(EntityManager em, String sql) {
    return em.createNativeQuery(sql).getResultList();
}


来源:https://stackoverflow.com/questions/57361468/spring-data-jpa-dynamic-sql-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!