简体   繁体   English

Spring 可变参数数据原生查询

[英]Spring data native query with variable quantity of parameters

I have a complex SQL query which may have different number of parameters in where section.我有一个复杂的 SQL 查询,它可能在 where 部分有不同数量的参数。 So, query sql should be constructed manually.因此,查询 sql 应该手动构建。 As a result, I get array of objects which contains 45 fields, each of them I will have to case, convert, etc. I can't use result set mapping because it requires a stable SQL which I should specify in annotation.结果,我得到了包含 45 个字段的对象数组,每个字段我都必须进行大小写、转换等。我不能使用结果集映射,因为它需要一个稳定的 SQL,我应该在注释中指定。 So the question is is there a way to return pojo or at least map with columns names rather than access all objects by index?所以问题是有没有办法用列名返回 pojo 或至少 map 而不是通过索引访问所有对象?

String sql = "select col1 as column1, ...., columnN as columnN from table where col1=2 ";

if(param1!=null){
   sql+=" AND param1="+param1;
}

....

Query q = manager.createNativeQuery(sql);

//getting list on object arrays of 45 fields, would like to have POJO or at least map
List list = q.getResultList();

If the table from where you retrieve your data is mapped in a POJO, you can specify manually the POJO by doing the following:如果您从中检索数据的表映射到 POJO,您可以通过执行以下操作手动指定 POJO:

Query query = em.createNativeQuery("SELECT * FROM table", MyPojoMappingTable.class);
@SuppressWarnings("unchecked")
List<MyPojoMappingTable> items = (List<MyPojoMappingTable>) query.getResultList();

On the contrary, if the table is not mapped in any POJO and you're in Spring, you could use jdbcTemplate to get at least a map:相反,如果表没有映射到任何 POJO 中并且您在 Spring 中,则可以使用jdbcTemplate至少获取 map:

@Autowired
NamedParameterJdbcTemplate jdbcTemplate;

String query;
Map<String, Object> queryParameters;

List<Map<String, Object>> rows = jdbcTemplate.queryForList(
    query,
    queryParameters
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM