亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

關于 Spring JdbcTemplate 的一些總結

發布時間:2020-07-23 16:48:02 來源:網絡 閱讀:567 作者:morningcat2018 欄目:編程語言

關于 Spring JdbcTemplate 的一些總結

一個小問題的思考

起因

當前項目中一直使用的都是 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 &lt;T&gt; List&lt;T&gt; query(String sql, RowMapper&lt;T&gt; rowMapper),只是將 Class&lt;T&gt; 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 實現類。

JdbcTemplate

https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/data-access.html#jdbc-JdbcTemplate

Query


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;
    }
}

Updating (INSERT, UPDATE, and DELETE)


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

Other

this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");

NamedParameterJdbcTemplate

https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/data-access.html#jdbc-NamedParameterJdbcTemplate

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

甘泉县| 开鲁县| 洞头县| 宜君县| 辉县市| 江川县| 民乐县| 临清市| 盐津县| 仙居县| 阳信县| 陕西省| 天津市| 沂南县| 美姑县| 大埔区| 正定县| 含山县| 济阳县| 六枝特区| 伽师县| 都昌县| 赤峰市| 体育| 楚雄市| 麻城市| 南康市| 柳河县| 洛隆县| 洛宁县| 巴马| 太康县| 图片| 博爱县| 唐山市| 松滋市| 阿拉尔市| 蚌埠市| 保山市| 武乡县| 荥经县|