3 回答

TA貢獻2080條經驗 獲得超4個贊
假設您已經配置了 Spring 數據源,您可以使用以下命令執行 Spring 本機查詢:
EntityManager em = emf.createEntityManager();
List<Object> results = em.createNativeQuery(query);
您還應該更新您的查詢,因為當狀態為空時您可以輕松獲得SQLException。如果發生這種情況,您將得到一個無效的查詢:
select *
from device
where and cinema_code = 'AL10' and content_profile = 'signage'
嘗試使用這個初始查詢:
"select * from device where 1=1 "
使用上面的內容,無論是否執行第一個 if 或根本不執行任何 if,查詢都將是正確的。

TA貢獻1828條經驗 獲得超6個贊
如果你不需要 JPA,你可以使用Spring JDBC
執行查詢:
String query = "select * from device where status = 2 and cinema_code = 'AL10' and content_profile = 'signage'";
List<Device> devices = jdbcTemplate.queryForObject(
? ? query, new Object[] { }, new DeviceRowMapper());
映射器可以如下所示:
public class DeviceRowMapper implements RowMapper<Device> {
? ? @Override
? ? public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
? ? ? ? Device device = new Device();
? ? ? ? device.setId(rs.getInt("ID"));
? ? ? ? ...
? ? ? ? return device;
? ? }
}
如何在提供url時配置連接
然而正如評論中提到的。最好不要連接字符串參數。您的查詢構建可以通過這種方式完成。
String query = "select * from device where";
List parameters =? new ArrayList();
boolean wasParameter = false;
if(status != null) {
? ? query += " status = ? ";
? ? parameters.add(status);
? ? wasParameter = true;
}
if(cinema != "") {
? ? query += (wasParameter ? " and ": "") +" cinema_code = ? ";
? ? parameters.add(cinema);
? ? wasParameter = true;
}
if(content_profile != "") {
? ? query += (wasParameter ? " and ": "") +" content_profile = ? ";
? ? parameters.add(content_profile);
? ? wasParameter = true;
}
if(mac != "") {
? ? query += (wasParameter ? " and ": "") +" mac = ? ";
? ? parameters.add(mac);
}
Object[] array = parameters.toArray(new Object[0]);
并執行查詢:
List<Device> devices = jdbcTemplate.queryForObject(
? ? query, array, new DeviceRowMapper());
添加回答
舉報