标签:
---恢复内容开始---
JdbcTemplate是线程安全的,所有Dao可以共享一个JdbcTemplate实例
举例
1 package org.zln.module_SpringJdbc.dao; 2 3 import org.springframework.jdbc.core.JdbcTemplate; 4 import org.springframework.jdbc.datasource.DriverManagerDataSource; 5 6 /** 7 * Created by sherry on 000006/7/6 9:51. 8 */ 9 public class TUserDao { 10 11 /*Spring JDBC创建表的例子*/ 12 public void createTable(){ 13 DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); 14 driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver"); 15 driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/JavaWeb"); 16 driverManagerDataSource.setUsername("root"); 17 driverManagerDataSource.setPassword("123456"); 18 19 JdbcTemplate jdbcTemplate = new JdbcTemplate(); 20 jdbcTemplate.setDataSource(driverManagerDataSource); 21 22 String sql = " CREATE table t_user(user_id int primary key,user_name varchar(60)) "; 23 jdbcTemplate.execute(sql); 24 25 } 26 }
当然,实际开发中不可能为每个方法创建一个JdbcTemplate实例
JdbcTemplate是对JDBC的一个浅浅的封装,但是大大方便了开发
Spring为几乎所有的模板类都提供了相应的支持类,和JdbcTemplate对应的支持类为JdbcDaoSupport。其内部定义了JdbcTemplate成员变量。我们可以通过扩展JdbcDaoSupport定义自己的Dao。
但现在Bean的注解已经成为主流,直接继承JdbcDaoSupport无法对JdbcTemplate成员变量使用注解。所以一般的做法是:自己定义一个Dao,在Dao中定义JdbcTemplate成员变量,打上注解。
实际项目中,还会在Dao中增加其它通用的功能,如声明JdbcTemplate,分页查询等
1 package org.zln.dao; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.jdbc.core.JdbcTemplate; 5 import org.springframework.stereotype.Repository; 6 7 /** 8 * Created by sherry on 000006/7/6 10:03. 9 */ 10 @Repository("baseDao") 11 public class BaseDao { 12 13 @Autowired 14 private JdbcTemplate jdbcTemplate; 15 16 }
JDBC细节:
JdbcTemplate内部通过PreparedStatement执行SQL语句,所以我们使用绑定参数的SQL,不会产生SQL注入问题。绑定参数索引从1开始,不是0
在DAO中尽量使用类级别的静态常量(final static)定义SQL字符串,不应在方法内部声明SQL字符串常量,提高JVM内存使用效率
更新操作
1 package org.zln.module_SpringJdbc.dao; 2 3 import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; 4 import org.springframework.stereotype.Repository; 5 import org.zln.dao.BaseDao; 6 import org.zln.module_SpringJdbc.domain.Forum; 7 8 import java.sql.Types; 9 10 /** 11 * Created by sherry on 000006/7/6 10:08. 12 */ 13 @Repository("forumDao") 14 public class ForumDao extends BaseDao{ 15 16 public void addForm(Forum forum){ 17 final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(?,?)"; 18 final Object[] params = new Object[]{forum.getForumName(), 19 forum.getForumDesc()}; 20 jdbcTemplate.update(sql, params, 21 new int[]{Types.VARCHAR, Types.VARCHAR}); 22 } 23 24 public void addForum(final Forum forum) { 25 final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(:forumName,:forumDesc)"; 26 // 使用BeanPropertySqlParameterSource参数源 27 // SqlParameterSource sps = new BeanPropertySqlParameterSource(forum); 28 // 使用MapSqlParameterSource参数名 29 MapSqlParameterSource sps = new MapSqlParameterSource(). 30 addValue("forumName", forum.getForumName()). 31 addValue("forumDesc",forum.getForumDesc()); 32 jdbcTemplate.update(sql, sps); 33 } 34 }
返回数据库的表自增主键
Hibernate等ORM框架中,保存对象的时候,如果主键是自增的(MySQL),会自动将自增的主键绑定到对象中。JDBC也可以。
在JDBC3.0规范中,当新增记录时,允许将数据库自动产生的主键值绑定到Statement或PreparedStatement
1 public void addForm(Forum forum){ 2 final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(?,?)"; 3 4 5 KeyHolder keyHolder = new GeneratedKeyHolder(); 6 jdbcTemplate.update(new PreparedStatementCreator() { 7 @Override 8 public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { 9 PreparedStatement preparedStatement = connection.prepareStatement(sql); 10 preparedStatement.setString(1,forum.getForumName()); 11 preparedStatement.setString(2,forum.getForumDesc()); 12 return preparedStatement; 13 } 14 },keyHolder); 15 forum.setForumId(keyHolder.getKey().intValue()); 16 17 }
批量更改
1 public void addForums(final List<Forum> forums) { 2 final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(?,?)"; 3 getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() { 4 public int getBatchSize() { 5 return forums.size(); 6 } 7 public void setValues(PreparedStatement ps, int index) 8 throws SQLException { 9 Forum forum = forums.get(index); 10 ps.setString(1, forum.getForumName()); 11 ps.setString(2, forum.getForumDesc()); 12 } 13 }); 14 }
查询
1 //单条查询 2 public Forum getForum(final int forumId) { 3 String sql = "SELECT forum_name,forum_desc FROM t_forum WHERE forum_id=?"; 4 final Forum forum = new Forum(); 5 jdbcTemplate.query(sql, new Object[]{forumId}, new RowCallbackHandler() { 6 public void processRow(ResultSet rs) throws SQLException { 7 forum.setForumId(forumId); 8 forum.setForumName(rs.getString("forum_name")); 9 forum.setForumDesc(rs.getString("forum_desc")); 10 } 11 }); 12 return forum; 13 }
多条List查询
1 public List getForums(final int fromId,final int toId) { 2 String sql = "SELECT forum_id,forum_name,forum_desc FROM t_forum WHERE forum_id between ? and ?"; 3 //使用RowCallbackHandler 4 // final List forums = new ArrayList(); 5 // getJdbcTemplate().query(sql,new Object[]{fromId,toId},new RowCallbackHandler(){ 6 // public void processRow(ResultSet rs) throws SQLException { 7 // Forum forum = new Forum(); 8 // forum.setForumId(rs.getInt("forum_id")); 9 // forum.setForumName(rs.getString("forum_name")); 10 // forum.setForumDesc(rs.getString("forum_desc")); 11 // forums.add(forum); 12 // }}); 13 // return forums; 14 return jdbcTemplate.query(sql,new Object[]{fromId,toId},new RowMapper(){ 15 public Object mapRow(ResultSet rs, int index) throws SQLException { 16 Forum forum = new Forum(); 17 forum.setForumId(rs.getInt("forum_id")); 18 forum.setForumName(rs.getString("forum_name")); 19 forum.setForumDesc(rs.getString("forum_desc")); 20 return forum; 21 } 22 23 }); 24 }
调用存储过程
1 public int getUserTopicNum(final int userId) { 2 String sql = "{call P_GET_TOPIC_NUM(?,?)}"; 3 //使用? Object execute(String callString, CallableStatementCallback action)接口 4 Object obj = jdbcTemplate.execute(sql,new CallableStatementCallback(){ 5 public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException { 6 cs.setInt(1,userId); 7 cs.registerOutParameter(2, Types.INTEGER); 8 cs.execute(); 9 return new Integer(cs.getInt(2)); 10 } 11 }); 12 return ((Integer)obj).intValue(); 13 }
标签:
原文地址:http://www.cnblogs.com/sherrykid/p/4623674.html