问题描述
我需要使用JPA通过匹配表中的2个分组参数来查找记录,但是我的问题是,即使有可能,我也不知道如何在SQL中传递对象或分组参数.
I need using JPA to find records by matching 2 grouped parameters from a table but my problem is that I don't know how to pass an object or grouped parameter in SQL, if that is possible at all.
假设我们有User表:
Let's say we have the User table:
USER_TABLE
name VARCHAR,
email VARCHAR,
address VARCHAR
我需要找到分组名称和电子邮件匹配的所有用户.像这样:
I need to find all users where grouped name and email match. Something like this:
SELECT FROM USER_TABLE
WHERE (name, email)
IN (('John', 'john@mail'), ('Oliver', 'oliver@mail'));
它在SQL工具中有效,但是现在我需要从Java使用此SQL
It works in SQL tool but now I need to use this SQL from Java
为此,我将其覆盖以接受参数
To do so I udpated it to accept a parameter
SELECT FROM USER_TABLE
WHERE (name, email)
IN (?);
所以我的问题是如何传递参数或将其分组?
So my question is HOW do I pass parameters or so that they will be grouped?
我试图创建一个如下所示的参数,但由于它不是有效类型而无法使用
I tried to create a parameter as it is below but it won't work because it is not a valid type
String param = "('John', 'john@mail'), ('Oliver', 'oliver@mail')";
db.execute(sql, param)
那有可能吗?
推荐答案
您可以这样做:
SELECT FROM USER_TABLE
WHERE (name, email)
IN ((?, ?), (?, ?));
每个参数代替一个单个标量值,而不是值列表,并且不替代任何其他SQL语法(例如括号).您需要将所有括号放入准备好的语句中,然后仅对值使用参数.
Each parameter takes the place of a single scalar value, not a list of values, and not any other SQL syntax like parentheses. You need to put all the parens into your prepared statement, then use parameters only for the values.
这篇关于如何将对象或分组参数传递给SQL IN子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!