使用 Spring DATA JPA 创建自定义查询? [英] Creating a custom query with Spring DATA JPA?

查看:39
本文介绍了使用 Spring DATA JPA 创建自定义查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring Data JPA 处理一个项目.我在数据库中有一个表作为 my_query.

I'm working on a project with Spring Data JPA. I have a table in the database as my_query.

我想创建一个将字符串作为参数的方法,然后在数据库中作为查询执行它.

I want to create a method which takes a string as a parameter, and then execute it as a query in the database.

方法:

executeMyQuery(queryString)

例如,当我通过时

queryString= "SELECT * FROM my_query"

然后它应该在数据库级别运行该查询.

then it should run that query in DB level.

存储库类如下.

public interface MyQueryRepository extends JpaRepository<MyQuery, Long>{
    public MyQuery findById(long id);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "?1", nativeQuery = true)
    public void executeMyQuery(String query);

}

然而,它并没有像我预期的那样工作.它给出了以下错误.

However, it didn't work as I expected. It gives the following error.

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 ''select * from my_query;'' at line 1

有没有其他方法可以实现这个目标.提前致谢

Is there any other way, that I could achieve this goal. Thanks in advance

推荐答案

唯一可以参数化的部分是 WHERE 子句中使用的值.考虑来自 官方文档:

The only part of it you can parameterise are values used in WHERE clause. Consider this sample from official doc:

public interface UserRepository extends JpaRepository<User, Long> {
  @Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
  User findByEmailAddress(String emailAddress);
}

这篇关于使用 Spring DATA JPA 创建自定义查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆