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

 

 

.

 

上一篇:SSM(Spring的数据库开发)


下一篇:纯手写超详细讲解Spring JdbcTemplate&声明式事务