jdbcTemplate使用的简单笔记

xiaoxiao2021-02-28  170

/** jdbcTmeplate的使用 其提供了增、删、改、查的方法 仔细说一下查询过程,其他的都差不多 单个查询: 1.他们都可以在sql中把参数写死 select * from table where id = 1; 2.但是如果要动态拼接参数的时候,jdbcTemplate提供了简单的接口来实现 在写sql的时候: select * from table where id = : id and name = : name 上边的 * 可有拼接得来 上边的 id = : id and name = : name 也可以拼接得来 其中where后面的是我们的查询参数,那么我们怎么才能让springJdbc知道我们的查询条件呢? where后便的 : id 类似于占位符,我们需要填充数据进去,这里应该使用Map结构的数据结构来填充数据 例如:**/ Map<String, Object> paramSorce = new HashMap<String, Object>(); paramSource.put("id", id); // 这里键值必须与 :后面的 标记一样,jdbcTemlate就是根据键值去填充我们用 : 标记的参数的 //然后调用接口去查询 jdbcTemplate.queryForObject(sql, paramSource, new MyRowMapper(record)); //其中record是类型为MyRecord的一个java对象引用 //结果回返回一个封装好的java对象,类型和 record类型一致为MyRecord //为什么回返回一个我们指定的java类型呢?并且还是封装好了我们的查询结果,这就需要我们研究一下RowMapper了 //下面是MyRowMapper的写法; public class MyRowMapper implements RowMapper<MyRecord>{ private MyRecord record; public MyRowMapper(){}; public MyRowMapper(MyRecord record){ this.record = record; } public MyRecord mapRow(ResultSet rs, int rowNum) throws SQLException{ //在这里我们创造指定类型的java对象,并且封装ResultSet中的查询数据 MyRecord records = new MyRecord(); if(record == null || record._name) records.setName(rs.getString(NAME)); //继续获取查询数据 这里 record 的作用 一个是指定返回的java类型, 一个是记录标识,用来封装我们想要封装的数据,所以我们可以事先指定record //中的标记,然后在这里按标记取值,所以它很重要 return records; } } /** 这里需要注意的是 1.实现RowMapper接口,并在<>中传入我们想要返回的java类型 2.复写mapRow(ResultSet rs, int rowNum) 方法,返回的类型因该与第一步的一致 查询多个 与单个查询过程一致,就是掉方法的时候用不同的接口,返回的是集合,他会自动把我们指定的返回类型的结果集封装成List集合 */ sql = "select * from table where id= : id"; paramSorce = new HashMap<String, Object>(); paramSource.put("id", id); jdbcTemplate.query(sql, paramSource, new MyRowMapper(record)); //返回一个Lisr<MyRecord>的集合 计数 sql = "select count(NAME) from table where AGE : age and WEIGHT : weight"; paramSource = new HashMap<String, Object>(); paramSource.put("age", age); paramSource.put("weight", weight); jdbcTemplate.queryForObject(sql, paramSource, Integer.class); //这里如果要返回基本类型,直接指定class类型就好 插入 sql = "insert into table (ID, NAME) values (:id, :name)"; paramSource = new HashMap<String, Object>(); paramSource.put("id" id); paramSource.put("name", name); jdbcTemplate.update(sql, paramSource); 更新 sql = "update table set NAME=:name, AGE=:age where ID=:id"; paramSource = new HashMap<String, Object>(); paramSource.put("id" id); paramSource.put("name", name); paramSource.put("age", age); jdbcTemplate.update(sql, paramSource); 删除 sql = "delete from table where ID=:id"; paramSource = new HashMap<String, Object>(); paramSource.put("id" id); jdbcTemplate.update(sql, paramSource); 其中 插入 更新 删除 都是使用update 方法,区别在于sql的写法和传的参数不一样,故能实现不同的功能 他们返回整型 1 成功 -1 失败
转载请注明原文地址: https://www.6miu.com/read-57576.html

最新回复(0)