本机查询问题

native query issues

我想创建一个标准查询,我可以在其中根据方法参数设置不同的实体属性和不同的值。

public List<Customer> searchBar(String entityProperty, String value) {

    String nativeQuery = "SELECT * FROM devices WHERE customer_id IN (SELECT customers.id FROM customers WHERE ? = ?)";
    Query query = session.createNativeQuery(nativeQuery);
    query.setParameter(1, entityProperty);
    query.setParameter(2, value);
    return query.getResultList();

您可以假设:

String entityProperty = "phoneNumber"
   String value = "222222222"

当我尝试这种方式时,我得到一个空结果,但如果我在 nativeQuery 语句上硬编码 entityProperty,它会按预期工作:

String nativeQuery = "SELECT * FROM devices WHERE customer_id IN (SELECT customers.id FROM customers WHERE phoneNumber = ?)";
Query query = session.createNativeQuery(nativeQuery);
query.setParameter(1, value);
return query.getResultList();

感谢您的宝贵时间:)

setParameter 用于设置列的值而不是列名。使用通用 Java 动态组成列名。如下所示,您应该明白了:

public List<Customer> searchBar(String entityProperty, String value) {

    String nativeQuery = String.format("SELECT * FROM devices WHERE customer_id IN (SELECT customers.id FROM customers WHERE %s = ?)",entityProperty);
    Query query = session.createNativeQuery(nativeQuery);
    query.setParameter(1, value);
    return query.getResultList();
}