我想创建一个条件查询,在其中可以根据方法args设置不同的实体属性和不同的值。
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语句上对entryProperty进行硬编码,它将按预期工作:
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();
感谢您的时间:)
答案 0 :(得分:0)
该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();
}