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

查看:158
本文介绍了使用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天全站免登陆