简体   繁体   English

如何使用 JPA 在本机插入查询中防止 SQL 注入?

[英]How to prevent SQL injection in native insert query with JPA?

I'm using a native query with JPA / Hibernate to perform an insert or update ("upsert") on PostgreSQL, depending whether an object exists or not.我正在使用 JPA / Hibernate 的本机查询在 PostgreSQL 上执行插入或更新(“upsert”),具体取决于 object 是否存在。 The code looks like this:代码如下所示:

val values: String = items.joinToString(", ", transform = this::convertItemToSqlValue)
val query = """
    insert into item (field1, field2)
    values $values
    on conflict on constraint item_pkey
    do update set 
        field1 = excluded.field1,
        field2 = excluded.field2
"""
entityManager.createNativeQuery(query).executeUpdate()

The function convertItemToSqlValue creates a String of the form ('value a', 123) . function convertItemToSqlValue创建一个形式为('value a', 123)的字符串。

A positional parameter ( values? ) didn't work (and led to a syntax error).位置参数( values? )不起作用(并导致语法错误)。

How could I prevent SQL injection with this kind of statmentement?我怎么能用这种声明来防止 SQL 注入呢?

Building SQL statements from user input dynamically is not the best idea.根据用户输入动态构建 SQL 语句并不是最好的主意。 It is better to use prepared statements.最好使用准备好的语句。 However there seems not be an easy way to perform patch updates with the JPA EntityManager in this case.但是,在这种情况下,似乎没有一种简单的方法可以使用 JPA EntityManager 执行补丁更新。

Setting multiple values is possible with JDBC. The following example show the usage with Spring's JdbcTemplate : JDBC 可以设置多个值。以下示例显示了Spring 的 JdbcTemplate的用法:

val items: List<Item> = ...

val statement = 
    """
    insert into item (field1, field2)
    values (?,?)
    on conflict on constraint arbeit_pkey
    do update set 
        field1 = excluded.field1,
        field2 = excluded.field2
    """
jdbcTemplate.batchUpdate(
    statement, 
    object : BatchPreparedStatementSetter {
        override fun setValues(statement: PreparedStatement, index: Int) {
            val item = items[index]
            statement.setString(1, item.field1)
            statement.setInt(2, item.field2)
        }
        override fun getBatchSize(): Int = items.size
    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM