Spring+JDBC: queryForXXX()|query()
Users u = template.queryForObject(sql,new BeanPropertyRowMapper(Users.class));
List users = template.query(sql,new BeanPropertyRowMapper(Users.class));
String sql = “select name from users”;
String name = template.queryForList(sql, String.class);
String sql = “select * from users”;
List<Map<String, Object>> list = template.queryForList(sql);
//调用存储过程 mydb->demo lambda
this.template.execute("{call demo(?,?)}", new CallableStatementCallback() {
@Override
public Object doInCallableStatement(CallableStatement cs)
throws SQLException, DataAccessException {
…
return out;
}
});
其他数据源配置:
使用dbcp连接池:导commons-dbcp-x.x.jar和commons-pool-x.x.jar
C3P0连接池:
阿里巴巴数据源:
来至于JNDI Java Naming and Directory Interface (使用tomcat作为实例)
//代表命名服务目录名称为jdbc/mysql(实际为:java:comp/env/jdbc/mysql)
//加上这个的意思是不用使用java:comp/env/来设置jndiName
或者使用:(导入jee命名空间)
<jee:jndi-lookup id=“dataSource” jndi-name=“jdbc/mysql” resource-ref=“true” />
理解template method模式
(其实就是与代理模式相反,将可变的业务拿出来,其他不变的模块组合成一个模板)
例如:
//重写了匿名类来实现功能
Integer execute = template.execute("{call demo(?,?)}", (CallableStatement
cs)-> {
cs.setObject(1, 50); cs.setObject(2, Types.INTEGER); return cs.getInt(2);
});

本文详细介绍了使用Spring框架结合JDBC进行数据访问的各种方法,包括使用queryForXXX(), query()等方法查询数据,以及调用存储过程的具体实现。同时,探讨了不同数据源配置方式,如dbcp、C3P0连接池和JNDI配置,并解析了template method设计模式的应用。
181

被折叠的 条评论
为什么被折叠?



