简体   繁体   English

Spring MappingSqlQuery的通用实现

[英]Generic Implementation of MappingSqlQuery in Spring

Currently, when we use MappingSqlQuery to get the resultset from DB, we do something like below: 当前,当我们使用MappingSqlQuery从数据库获取结果集时,我们将执行以下操作:

Extends MappingSqlQuery 扩展MappingSqlQuery

In the above example, we have a class LastNameAndAgeQuery extends from MappingSqlQuery, and we applied mapRow method. 在上面的示例中,我们从MappingSqlQuery扩展了一个LastNameAndAgeQuery类,并应用了mapRow方法。 However, if I want to make some changes in query, let's say I want to add one more info of employee, their birthday. 但是,如果我想在查询中进行一些更改,那么我想添加一个雇员的信息,即他们的生日。 In this way, I have to add: 这样,我必须添加:

employee.setBirthday(resultSet.getInt("birthday"));

in maprow method and in the employee class, I have to add field Birthday and write set and get method. 在maprow方法和员工类中,我必须添加字段Birthday,并编写set和get方法。

Is there a generic implementation that if I want to modify query, all I need to do is modify query itself, I don't need to change the maprow method, and add field in employee class. 是否有一个通用的实现,如果我想修改查询,我所要做的就是修改查询本身,不需要更改maprow方法,并在employee类中添加字段。 Or a better way to do this. 或者是更好的方法。

Thank you in advance. 先感谢您。

You might want to look at ORM (Object Relational Mapping) solution such as Hibernate or JPA (Java Persistence API). 您可能想看看ORM(对象关系映射)解决方案,例如Hibernate或JPA(Java Persistence API)。 Typically using ORM you only need to manipulate the POJO (Plain Old Java Object) that represents your table row, and the ORM API will translate that into SQL 通常,使用ORM只需操作代表表行的POJO(普通旧Java对象),ORM API会将其转换为SQL

The only way if you want to continue to keep jdbcTemplate is to go in for generic row mappers like use a map or use the queryForMap api's, so you can modify the query to have more columns and access the map to read its content. 如果要继续保留jdbcTemplate ,唯一的方法是使用诸如使用地图或使用queryForMap api之类的通用行映射器,因此可以修改查询以具有更多列并访问该地图以读取其内容。

But do keep in mind that concrete row mappers increase readability and easy to maintain. 但是请记住,具体的行映射器可提高可读性并易于维护。

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

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