日期:2014-05-16  浏览次数:20390 次

Spring:Spring中集成JDBC;
Spring将数据访问过程中固定的和可变的部分明确划分为两个不同的类:模板(template)和回调(callback)。   
模板类处理数据访问的固定部分---事物控制、管理资源,处理异常。


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