hibernate中sql查询 字段如何与属性映射

 

  在维护旧的项目时,由于好久没有使用hibernate,导致很多都比较生疏。自己写sql 查询字段和对象中的属性 需要一一映射。

  使用jdbcTemplate.queryForObject()等方法时,有可能报错:Incorrect column count: expected 1, actual 5

  1.反例:

     StringBuffer sql = new StringBuffer();
        sql.append("select pcb.bid, pcb.brand, pcb.brand_code brandCode, pcb.bra_country braCountry, pcb.identifying_photo identifyingPhoto, pcb.bra_letter braLetter, pcb.last_operator_name lastOperatorName,");
        sql.append(" pcb.last_operator_id lastOperatorId, pcb.parent_id parentId, pcb.create_time createTime, pcb.update_time updateTime");
        sql.append(" from platform_carbrand subpcb inner join platform_carbrand pcb on subpcb.parent_id = pcb.bid");
        sql.append(" where subpcb.bid = " + subBrandId);
Carbrand carbrand
= jdbcTemplate.queryForObject(sql.toString(), Carbrand.class);

 

  2.解决方式 通过查询多条或一条的正例:

        List<Carbrand> carbrandList = jdbcTemplate.query(sql.toString(), new Object[]{}, new BeanPropertyRowMapper<Carbrand>(Carbrand.class));
        if (CollectionUtils.isEmpty(carbrandList)) {
            return null;
        }
        return carbrandList.get(0);

 

 

.

 

posted @ 2021-08-18 14:50  黄小葱  阅读(304)  评论(0编辑  收藏  举报