我是靠谱客的博主 想人陪豌豆,最近开发中收集的这篇文章主要介绍解决使用springboot+ jpa + @query原生sql查询,无法动态插入表名的问题,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

问题描述:

在使用springboot2.0 + jpa+ @query原生sql查询时,无法动态插入表名

public interface BalanceTargetInfoRepositoryWithNativeQuery extends JpaRepository<BalanceTargetInfoBean, Long> {
/**
*
不能使用,问题:动态传入表名,会在拼接sql时带单引号,导致sql执行失败
* @param memberId
* @return
*/
@Query(nativeQuery = true,value = " SELECT " +
"id AS targetId, " +
"state AS state,n" +
"reduce AS reduce,n" +
"end_date AS endDate,n" +
"start_date AS startDate,n" +
"target_name AS targetName,n" +
"target_value AS targetValue,n" +
"complete_rate AS completeRate,n" +
"current_value AS currentValue,n" +
"DATEDIFF(end_date, CURRENT_DATE()) AS remainingDay,n" +
"notification AS notification FROM :tableNamen" +
"WHERE member_id = :memberIdn" +
"ORDER BY update_time DESC;")
List<Object[]> getTarget(@Param("tableName")String tableName, @Param("memberId")long memberId);
}

使用 ?1传递表名也是报下面的错误。会自动给表名添加单引号,导致sql无法执行。 

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''target_info_0'
WHERE member_id = 7387250

解决:使用实体管理器EntityManager

@Component
public class BalanceTargetInfoRepository {
//注入的是实体管理器,执行持久化操作
@PersistenceContext
EntityManager entityManager;
public
List<Object[]> getTarget(String tableName, long memberId){
String sql=" SELECT " +
"id AS targetId, " +
"state AS state,n" +
"reduce AS reduce,n" +
"end_date AS endDate,n" +
"start_date AS startDate,n" +
"target_name AS targetName,n" +
"target_value AS targetValue,n" +
"complete_rate AS completeRate,n" +
"current_value AS currentValue,n" +
"DATEDIFF(end_date, CURRENT_DATE()) AS remainingDay,n" +
"notification AS notification FROM "+tableName+" WHERE member_id ="+memberId+" ORDER BY update_time DESC;";
List<Object[]> list = entityManager.createNativeQuery(sql).getResultList();
return list;
}
}

 

最后

以上就是想人陪豌豆为你收集整理的解决使用springboot+ jpa + @query原生sql查询,无法动态插入表名的问题的全部内容,希望文章能够帮你解决解决使用springboot+ jpa + @query原生sql查询,无法动态插入表名的问题所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部