【问题标题】:Spring JPA writing a native query with parameters inside single quotesSpring JPA 使用单引号内的参数编写本机查询
【发布时间】:2018-08-01 16:03:36
【问题描述】:
@Repository
public class PostgresRepository {

@PersistenceContext
EntityManager entityManager;

@Autowired
private JdbcTemplate jdbcTemplate;

public void updatePassword(PostgresDto postgresDto) {

    Query result = entityManager.createNativeQuery("ALTER ROLE :username PASSWORD :password ")
            .setParameter(1,postgresDto.getUsername())
            .setParameter(2,postgresDto.getPassword());
    int results = result.executeUpdate();

    }
}

我正在尝试让 Spring JPA 通过本机查询更改 postgres 数据库的角色密码。在设置本机查询的参数时遇到问题。更改角色的postgres语句如下ALTER ROLE username PASSWORD 'password'

错误:

org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 138 common frames omitted
 Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1" Position: 12 

【问题讨论】:

    标签: java spring postgresql jpa


    【解决方案1】:

    查询中缺少关键字。应该是:

    ALTER ROLE :username WITH PASSWORD :password
    

    【讨论】:

    • 这不能作为原生查询使用,因为 alter role 语句类似于 ALTER ROLE davide WITH PASSWORD 'hu8jmn3';并且使用 JPA 原生查询从参数中解析出单引号
    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    相关资源
    最近更新 更多