模板类处理数据访问的固定部分---事物控制、管理资源,处理异常。
spring访问数据库的模板:
jca.cci.support.CciDaoSupport JCA CCI connections jdbc.core.support.JdbcDaoSupport JDBC connections jdbc.core.namedparam.NamedParameterJdbcDaoSupport JDBC connections with support for named parameters jdbc.core.simple.SimpleJdbcDaoSupport JDBC connections, simplified with Java 5 constructs orm.hibernate.support.HibernateDaoSupport Hibernate 2.x sessions orm.hibernate3.support.HibernateDaoSupport Hibernate 3.x sessions orm.ibatis.support.SqlMapClientDaoSupport iBATIS SqlMap clients orm.jdo.support.JdoDaoSupport Java Data Object implementations orm.jpa.support.JpaDaoSupport Java Persistence API entity managers
配置数据源:
对于即将发布到生产环境的应用程序,我建议使用从连接池获取连接的数据源,如果可能的话,我倾向于通过应用服务器的JNDI来获取池中数据源。
spring应用程序经常部署在JAVA EE 应用服务器在,如websphere jboss 或者像tomcat这样的web容器,这些服务器允许你配置通过JNDI获取数据源。这种配置的好处在于数据源完全可以在应用程序之外进行管理。这样应用程序只需要在访问数据库的时候访问数据源就可以了。 另外,在应用服务器在管理的数据源通常以池的方式组织,从而具备更好的性能,并且支持系统管理员对其进行热切换。
<jee:jndi-lookupid="dataSource" jndi-name="/jdbc/SpitterDS" resource-ref="true"/>
这样可以装配到Spring中了。
使用数据源连接池:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <propertyname="driverClassName"value="org.hsqldb.jdbcDriver"/> <propertyname="url" value="jdbc:hsqldb:hsql://localhost/spitter/spitter"/> <propertyname="username"value="sa"/> <propertyname="password"value=""/> <propertyname="initialSize"value="5"/> <propertyname="maxActive"value="10"/> </bean>
下面是连接池属性:
initialSize The number of connections created when the pool is started. maxActive The maximum number of connections that can be allocated from the pool at the same time. If zero, there’s no limit. maxIdle The maximum number of connections that can be idle in the pool without extras being released. If zero, there’s no limit. maxOpenPreparedStatements The maximum number of prepared statements that can be allo- cated from the statement pool at the same time. If zero, there’s no limit. maxWait How long the pool will wait for a connection to be returned to the pool (when there are no available connections) before an exception is thrown. If -1, wait indefinitely. minEvictableIdle TimeMillis How long a connection can remain idle in the pool before it’s eligible for eviction. minIdle The minimum number of connections that can remain idle in the pool without new connections being created. poolPreparedStatements Whether or not to pool prepared statements (Boolean).
Spring--------JDBC模板
<!-- 声明jdbc模板,使用中须要引用数据库--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate"> <constructor-argref="dataSource"/> </bean> public classJdbcSpitterDAOimplementsSpitterDAO{ ... privateSimpleJdbcTemplatejdbcTemplate; public voidsetJdbcTemplate(SimpleJdbcTemplatejdbcTemplate){ this.jdbcTemplate=jdbcTemplate; } } <!-- 调用jdbc模板--> <bean id="spitterDao" class="com.habuma.spitter.persistence.SimpleJdbcTemplateSpitterDao"> <propertyname="jdbcTemplate"ref="jdbcTemplate"/> </bean>
//这段代码执行update的时候,会获取连接,创建语句,并执行sql public voidaddSpitter(Spitterspitter){ jdbcTemplate.update(SQL_INSERT_SPITTER, spitter.getUsername(), spitter.getPassword(), spitter.getFullName(), spitter.getEmail(), spitter.isUpdateByEmail()); spitter.setId(queryForIdentity()); } public SpittergetSpitterById(longid){ return jdbcTemplate.queryForObject( SQL_SELECT_SPITTER_BY_ID, new ParameterizedRowMapper<Spitter>(){ public SpittermapRow(ResultSetrs,introwNum) throws SQLException{ Spitter spitter=newSpitter(); spitter.setId(rs.getLong(1)); spitter.setUsername(rs.getString(2)); spitter.setPassword(rs.getString(3)); spitter.setFullName(rs.getString(4)); return spitter; } }, id ); }
注:queryForObject方法有三个参数: 1、string,包含要从数据库中查找的sql。2、ParameterizedRowMapper回调方法 3、可变参数列表,列出了要绑定到查询上的索引参数值。
使用命名参数:
private static final String SQL_INSERT_SPITTER= "insert into spitter(username,password,fullname)"+ "values(:username,:password,:fullname)"; public void addSpitter(Spitter spitter){ Map<String,Object>params=new HashMap<String,Object>(); params.put("username",spitter.getUsername()); params.put("password",spitter.getPassword()); params.put("fullname",spitter.getFullName()); jdbcTemplate.update(SQL_INSERT_SPITTER,params); spitter.setId(queryForIdentity()); }
SimpleJdbcDaoSupport,通过getSimpleJdbcTemplate()能够便捷地访问SimpleJdbcTemplete. 如下:
public voidaddSpitter(Spitterspitter){ getSimpleJdbcTemplate().update(SQL_INSERT_SPITTER, spitter.getUsername(), spitter.getPassword(), spitter.getFullName(), spitter.getEmail(), spitter.isUpdateByEmail()); spitter.setId(queryForIdentity()); }
<!-- SimpleJdbcDaoSupport类须要用到数据源--> <bean id="spitterDao" class="com.habuma.spitter.persistence.JdbcSpitterDao"> <property name="dataSource" ref="dataSource"/> </bean>