老熟女激烈的高潮_日韩一级黄色录像_亚洲1区2区3区视频_精品少妇一区二区三区在线播放_国产欧美日产久久_午夜福利精品导航凹凸

重慶分公司,新征程啟航

為企業(yè)提供網(wǎng)站建設(shè)、域名注冊、服務器等服務

關(guān)于SpringJdbcTemplate的一些總結(jié)

關(guān)于 Spring JdbcTemplate 的一些總結(jié)

一個小問題的思考

起因

當前項目中一直使用的都是 SpringData JPA ,即 public interface UserRepository extends JpaRepository<User, Serializable> 這種用法;

成都創(chuàng)新互聯(lián)公司堅持“要么做到,要么別承諾”的工作理念,服務領(lǐng)域包括:成都網(wǎng)站建設(shè)、做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務,滿足客戶于互聯(lián)網(wǎng)時代的金林網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

考慮到 SpringData JPA 確實有一定的局限性,在部分查詢中使用到了 JdbcTemplate 進行復雜查詢操作;
由于本人16年也曾使用過 JdbcTemplate,古語溫故而知新,所以做此總結(jié)梳理。

首先列出同事的做法:

public class xxx{

    xxx method(){
        ...
        List list = jdbcTemplate.query(sql, new WishDTO());
        ...
    }
}

@Data
public class WishDTO implements RowMapper, 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 再實現(xiàn)實現(xiàn)一遍 RowMapper 有點麻煩,畢竟 WishDTO 實體類的所有字段都是需要賦值的,并沒有定制化需求。

所以想著有沒有更好地寫法,然后就翻了一下 jdbcTemplate 的方法,找到了一個自認為滿足自己這個需求的方法:

public List queryForList(String sql, Class elementType)
即 將代碼改為:

public class xxx{
xxx method(){
    ...
    List list = jdbcTemplate.queryForList(sql, WishDTO.class);
    ...
}

}

@Data
public class WishDTO implements Serializable {
String xxx;
Long xxx;
Date xxx;
BigDecimal xxx;
}


一切看起來都很完美,但執(zhí)行卻報錯了:**Incorrect column count: expected 1, actual 13**

### 思考

經(jīng)過一番對源碼進行debug,結(jié)合網(wǎng)上的一些資料,大概知道了是什么原因了,分析如下;

```java
    public  List queryForList(String sql, Class elementType) throws DataAccessException {
        return query(sql, getSingleColumnRowMapper(elementType));
    }

其本質(zhì)是還是調(diào)用public <T> List<T> query(String sql, RowMapper<T> rowMapper),只是將 Class<T> elementType 封裝成一個 RowMapper 實現(xiàn)實例;

    protected  RowMapper getSingleColumnRowMapper(Class requiredType) {
        return new SingleColumnRowMapper<>(requiredType);
    }

現(xiàn)在我們可以看一下 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.
 *
 * 

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 的 簡單實現(xiàn),且僅能接收一個字段的數(shù)據(jù),如 String.class 和 Integer.class 等基礎(chǔ)類型;

網(wǎng)上的參考資料:https://blog.csdn.net/qq_40147863/article/details/86035595

解決方案

使用 BeanPropertyRowMapper 進行封裝 ;
即 將代碼改為:

public class xxx{

    xxx method(){
        ...
        List list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(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.
 *
 * 

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. * *

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. * *

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". * *

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. * *

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 轉(zhuǎn)化成相對應的 Bean RowMapper 實現(xiàn)類。

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() {
            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 actors = this.jdbcTemplate.query(
        "select first_name, last_name from t_actor",
        new RowMapper() {
            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 findAllActors() {
    return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper());
}
private static final class ActorMapper implements RowMapper {
    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


當前題目:關(guān)于SpringJdbcTemplate的一些總結(jié)
文章起源:http://www.xueling.net.cn/article/jdgeci.html

其他資訊

在線咨詢
服務熱線
服務熱線:028-86922220
TOP
主站蜘蛛池模板: 缅甸午夜性猛交xxxx | 新白娘子传奇50集免费赵雅芝版 | 国产精品久久久久久久久鸭 | 99久久精品无免国产免费 | 自拍偷拍视频亚洲 | 亚洲午夜福利AV一区二区无码 | 四虎影视网 | 五月天人体艺术 | 色婷婷一区 | 国产成人69视频午夜福利在线观看 | 一级aaaa毛片 | 婷婷六月国产精品久久不卡 | 抖音奶片无罩子52秒回放 | 办公室强伦片免费看 | 色先锋aa成人 | 精品国产精品国产自在久国产 | 亚洲蜜桃V妇女 | 国语自产精品视频在线区 | 欧美嫩交一区二区三区 | 亚洲一区二区在线看 | 亚洲中文久久精品无码软件 | 免费的又色又爽又黄的片捆绑美女 | 亚洲国产精品999久久久婷婷 | 国产在线欧美日韩精品一区 | 亚洲国产精品无码久久久久久曰 | 四虎海外永久免费网址 | 麻豆精品在线 | 久久久久久久久久久99 | 精品无码人妻一区二区免费蜜桃 | 男女男精品视频网站 | 国产精品免费久久影 | 中文字幕AV一区乱码 | 精品中文字幕视频 | 中文精品无码中文字幕无码专区 | 人妻少妇久久中文字幕 | 免费精品国产福利片 | 亚洲精品日本无v一区 | 久久狠狠高潮亚洲精品 | 午夜伦理片在线观看 | 亚洲va | 久久精品久久精品亚洲人 |