3 回答

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

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果你不需要 JPA,你可以使用Spring JDBC
執(zhí)行查詢:
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時(shí)配置連接
然而正如評(píng)論中提到的。最好不要連接字符串參數(shù)。您的查詢構(gòu)建可以通過這種方式完成。
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]);
并執(zhí)行查詢:
List<Device> devices = jdbcTemplate.queryForObject(
? ? query, array, new DeviceRowMapper());
添加回答
舉報(bào)