回答

收藏

使用Spring DATA JPA创建自定义查询?

技术问答 技术问答 114 人阅读 | 0 人回复 | 2023-09-13

我正在使用Spring Data JPA进行项目。我在数据库中有一个表作为my_query。
1 V2 z3 B# X/ D8 w% h$ t我想创建一个将字符串作为参数的方法,然后将其作为数据库中的查询执行。! `/ d# I: ~2 d
方法:( B! o2 L# Y# a0 U
executeMyQuery(queryString)
% B% b) B4 A3 u% o: e' h/ }8 X4 K例如,当我通过
. h0 V& p$ q( N/ tqueryString= "SELECT * FROM my_query"; A5 y6 l  K, F( ?: j4 z5 [/ k9 Z
那么它应该在数据库级别运行该查询。  W& A* [9 J* S+ D/ o8 n1 \; U
存储库类如下。% e, m! J6 X% j" T
public interface MyQueryRepository extends JpaRepository{$ H' Q* C# ]1 [) N3 M& i7 Z5 R' r
    public MyQuery findById(long id);
1 T4 [& {/ V! [) M4 N: i1 j6 V" s- _    @Modifying(clearAutomatically = true): y% D6 v4 F, H. W+ M; A
    @Transactional
4 C$ a3 h3 m& m- T3 K( B2 U    @Query(value = "?1", nativeQuery = true)" K* I# N2 b, k& L3 _
    public void executeMyQuery(String query);4 u7 R6 f1 Z3 K9 X8 i
}: F. R* z, j. D6 x9 Y: V4 w
但是,它没有按我预期的那样工作。它给出以下错误。
3 r3 k' \- H# t) r- a$ o/ NCaused 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 ''select * from my_query;'' at line 1
, P! [; f( m7 j( Z还有什么其他方法可以实现这个目标。提前致谢
- Z2 j9 G! Z" h3 ~1 }- _                , L1 A  J% g4 L# }+ s
解决方案:
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则