您好,登錄后才能下訂單哦!
當前項目中一直使用的都是 SpringData JPA
,即 public interface UserRepository extends JpaRepository<User, Serializable>
這種用法;
考慮到 SpringData JPA
確實有一定的局限性,在部分查詢中使用到了 JdbcTemplate
進行復雜查詢操作;
由于本人16年也曾使用過 JdbcTemplate
,古語溫故而知新,所以做此總結梳理。
首先列出同事的做法:
public class xxx{
xxx method(){
...
List<WishDTO> list = jdbcTemplate.query(sql, new WishDTO());
...
}
}
@Data
public class WishDTO implements RowMapper<WishDTO>, Serializable {
String xxx;
Long xxx;
Date xxx;
BigDecimal xxx;
@Override
public WishDTO mapRow(ResultSet rs, int rowNum) {
WishDTO dto = new WishDTO();
Field[] fields = dto.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
field.set(dto, rs.getObject(field.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
return dto;
}
}
個人感覺讓 WishDTO 再實現實現一遍 RowMapper 有點麻煩,畢竟 WishDTO 實體類的所有字段都是需要賦值的,并沒有定制化需求。
所以想著有沒有更好地寫法,然后就翻了一下 jdbcTemplate 的方法,找到了一個自認為
滿足自己這個需求的方法:
public <T> List<T> queryForList(String sql, Class<T> elementType)
即 將代碼改為:public class xxx{
xxx method(){
...
List<WishDTO> list = jdbcTemplate.queryForList(sql, WishDTO.class);
...
}
}
@Data
public class WishDTO implements Serializable {
String xxx;
Long xxx;
Date xxx;
BigDecimal xxx;
}
一切看起來都很完美,但執行卻報錯了:**Incorrect column count: expected 1, actual 13**
### 思考
經過一番對源碼進行debug,結合網上的一些資料,大概知道了是什么原因了,分析如下;
```java
public <T> List<T> queryForList(String sql, Class<T> elementType) throws DataAccessException {
return query(sql, getSingleColumnRowMapper(elementType));
}
其本質是還是調用public <T> List<T> query(String sql, RowMapper<T> rowMapper)
,只是將 Class<T> elementType
封裝成一個 RowMapper
實現實例;
protected <T> RowMapper<T> getSingleColumnRowMapper(Class<T> requiredType) {
return new SingleColumnRowMapper<>(requiredType);
}
現在我們可以看一下 SingleColumnRowMapper 類的描述:
/**
* {@link RowMapper} implementation that converts a single column into a single
* result value per row. Expects to operate on a {@code java.sql.ResultSet}
* that just contains a single column.
*
* <p>The type of the result value for each row can be specified. The value
* for the single column will be extracted from the {@code ResultSet}
* and converted into the specified target type.
*/
其實從類名也可以看出,這是一個 RowMapper 的 簡單實現,且僅能接收一個字段的數據,如 String.class 和 Integer.class 等基礎類型;
網上的參考資料:https://blog.csdn.net/qq_40147863/article/details/86035595
使用 BeanPropertyRowMapper 進行封裝 ;
即 將代碼改為:
public class xxx{
xxx method(){
...
List<WishDTO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<WishDTO>(WishDTO.class));
...
}
}
@Data
public class WishDTO implements Serializable {
String xxx;
Long xxx;
Date xxx;
BigDecimal xxx;
}
接下來看一下 BeanPropertyRowMapper
的類描述:
/**
* {@link RowMapper} implementation that converts a row into a new instance
* of the specified mapped target class. The mapped target class must be a
* top-level class and it must have a default or no-arg constructor.
*
* <p>Column values are mapped based on matching the column name as obtained from result set
* meta-data to public setters for the corresponding properties. The names are matched either
* directly or by transforming a name separating the parts with underscores to the same name
* using "camel" case.
*
* <p>Mapping is provided for fields in the target class for many common types, e.g.:
* String, boolean, Boolean, byte, Byte, short, Short, int, Integer, long, Long,
* float, Float, double, Double, BigDecimal, {@code java.util.Date}, etc.
*
* <p>To facilitate mapping between columns and fields that don't have matching names,
* try using column aliases in the SQL statement like "select fname as first_name from customer".
*
* <p>For 'null' values read from the database, we will attempt to call the setter, but in the case of
* Java primitives, this causes a TypeMismatchException. This class can be configured (using the
* primitivesDefaultedForNullValue property) to trap this exception and use the primitives default value.
* Be aware that if you use the values from the generated bean to update the database the primitive value
* will have been set to the primitive's default value instead of null.
*
* <p>Please note that this class is designed to provide convenience rather than high performance.
* For best performance, consider using a custom {@link RowMapper} implementation.
*/
其作用就是講一個Bean class 轉化成相對應的 Bean RowMapper 實現類。
https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/data-access.html#jdbc-JdbcTemplate
int rowCount = this.jdbcTemplate.queryForObject("select count(*) from t_actor", Integer.class);
int countOfActorsNamedJoe = this.jdbcTemplate.queryForObject("select count(*) from t_actor where first_name = ?", Integer.class, "Joe");
String lastName = this.jdbcTemplate.queryForObject("select last_name from t_actor where id = ?", new Object[]{1212L}, String.class);
Actor actor = this.jdbcTemplate.queryForObject(
"select first_name, last_name from t_actor where id = ?",
new Object[]{1212L},
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
List<Actor> actors = this.jdbcTemplate.query(
"select first_name, last_name from t_actor",
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
---
public List<Actor> findAllActors() {
return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper());
}
private static final class ActorMapper implements RowMapper<Actor> {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
}
this.jdbcTemplate.update(
"insert into t_actor (first_name, last_name) values (?, ?)",
"Leonor", "Watling");
this.jdbcTemplate.update(
"update t_actor set last_name = ? where id = ?",
"Banjo", 5276L);
this.jdbcTemplate.update(
"delete from actor where id = ?",
Long.valueOf(actorId));
this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/data-access.html#jdbc-NamedParameterJdbcTemplate
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。