亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Java Spring 中執行預構建查詢

如何在 Java Spring 中執行預構建查詢

紅糖糍粑 2023-09-20 16:11:34
我需要在java spring中執行預構建的SQL查詢,我創建的查詢如下,String query = "select * from device where";if (status != null) {    query += " status = "+status;}if (cinema != "") {    query += " and cinema_code = \'"+cinema+"\'";}if (content_profile != "") {    query += " and content_profile = \'"+content_profile+"\'";}if (mac != "") {    query += " and mac = \'"+mac+"\'";}構建查詢:select * from device where status = 2   and cinema_code = 'AL10'   and content_profile = 'signage'
查看完整描述

3 回答

?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

您可以使用 Spring Data JPA 規范進行動態查詢。

查看完整回答
反對 回復 2023-09-20
?
犯罪嫌疑人X

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,查詢都將是正確的。


查看完整回答
反對 回復 2023-09-20
?
30秒到達戰場

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());


查看完整回答
反對 回復 2023-09-20
  • 3 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號