通过数据源DataSource连接数据库对象Connection:现在Spring通过配置文件获取数据源DataSource,帮助我们管理Connection对象
Spring获取DataSource有四种方式获取:将数据源DataSource注入到Bean容器中,通过数据源去获取连接池中连接
基于JDK规范提供的DataSource数据源:
<bean name="dataSource1" class="oracle.jdbc.pool.OracleConnectionPoolDataSource">
<property name="networkProtocol">
<value>tcpvalue>
property>
<property name="databaseName">
<value>XEvalue>
property>
<property name="driverType">
<value>thinvalue>
property>
<property name="portNumber">
<value>1521value>
property>
<property name="user">
<value>briupvalue>
property>
<property name="serverName">
<value>127.0.0.1value>
property>
<property name="password">
<value>briupvalue>
property>
bean>
dbcp: DBCP(DataBase connection pool),数据库连接池。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。
<context:property-placeholder location="classpath:oracle.properties" />
或者
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="classpath:oracle.properties" />
bean>
<bean name="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${driver}value>
property>
<property name="url">
<value>${url}value>
property>
<property name="username">
<value>${user}value>
property>
<property name="password">
<value>${password}value>
property>
<property name="maxActive">
<value>80value>
property>
<property name="maxIdle">
<value>20value>
property>
<property name="maxWait">
<value>3000value>
property>
bean>
Spring提供的DataSource数据源对象注入到容器
<context:property-placeholder location="classpath:oracle.properties" />
<bean name="dataSource3"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${driver}value>
property>
<property name="url">
<value>${url}value>
property>
<property name="username">
<value>${user}value>
property>
<property name="password">
<value>${password}value>
property>
bean>
c3p0: C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目开有Hibernate、Spring等。
c3p0:有自动回收空闲连接的功能
dbcp:没有自动回收空闲连接的功能
<context:property-placeholder location="classpath:oracle.properties" />
<bean name="dataSource4" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${driver}value>
property>
<property name="jdbcUrl">
<value>${url}value>
property>
<property name="user">
<value>${user}value>
property>
<property name="password">
<value>${password}value>
property>
<property name="minPoolSize">
<value>5value>
property>
<property name="maxPoolSize">
<value>30value>
property>
<property name="initialPoolSize">
<value>10value>
property>
<property name="maxIdleTime">
<value>60value>
property>
<property name="acquireIncrement">
<value>5value>
property>
<property name="idleConnectionTestPeriod">
<value>60value>
property>
<property name="acquireRetryAttempts">
<value>30value>
property>
bean>
Test测试,数据源DataSource获取数据库连接
public class JdbcDao implements AccountDao{
//数据源
private DataSource dataSorce;
public DataSource getDataSorce() {
return dataSorce;
}
public void setDataSorce(DataSource dataSorce) {
this.dataSorce = dataSorce;
}
@Override
public void update(int id, double balance) {
try {
Connection conn =
dataSorce.getConnection();
System.out.println("conn = "+conn);
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<!-- 配置文件中将JdbcDao对象注入到Bean容器中,注入依赖,将容器中DataSource对象和dao对象关联起来,通过DataSource的getConnection方法获取连接 -->
<bean name="dao" class="com.briup.db.jdbc.JdbcDao">
<property name="dataSorce" ref="dataSource4"></property>
</bean>
测试方法
@Test
public void jdbc_dataSource(){
try {
String path = "com/briup/db/jdbc/jdbc.xml";
ClassPathXmlApplicationContext container =
new ClassPathXmlApplicationContext(path);
AccountDao dao = (AccountDao) container.getBean("dao");
dao.update(1, 1000);
container.destroy();
}catch(Exception e) {
e.printStackTrace();
}
}
Spring提供了org.springframework.jdbc.core.JdbcTemplate:这是Spring中JDBC核心包的类,用来简化JDBC使用
JdbcTemplate类中存在执行SQL语句对应方法(增,删,改,查)
JdbcTemplate模板类如何使用:在htmlsingle中搜索即可,其中包含有大量的使用实例。
//Spring使用文档中jdbcTemplate使用实例
queryForObject,query方法:查询方法
//queryForObject方法查询数据条数
int rowCount = this.jdbcTemplate.queryForObject("select count(*) from t_actor", int.class);
//queryForObject方法传入Object数组存储的Long类型id,查询对应的名字
String lastName = this.jdbcTemplate.queryForObject(
"select last_name from t_actor where id = ?",
new Object[]{12L}, String.class);
//queryForObject方法查询一条数据通过匿名内部类映射为一个自定义Actor类型的对象
Actor actor = this.jdbcTemplate.queryForObject(
"select first_name, last_name from t_actor where id = ?",
new Object[]{12L},
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
//query方法查询多条数据,封装为多个自定义类型对象
List<Actor> actors = this.jdbcTemplate.query(
"select first_name, last_name from t_actor",
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
update方法:执行DML语句的insert,update,delete
//update方法插入数据
this.jdbcTemplate.update(
"insert into t_actor (first_name, last_name) values (?, ?)",
"Leonor", "Watling");
//update方法更新数据
this.jdbcTemplate.update(
"update t_actor set last_name = ? where id = ?",
"Banjo", 5276L);
//update方法删除数据
this.jdbcTemplate.update(
"delete from actor where id = ?",
Long.valueOf(actorId));
Jdbc的操作语言的事物默认是自动提交的。
dao层获得jdbcTemplate对象
public class JdbcTemplateDao implements AccountDao {
private JdbcTemplate jdbcTemplate;
@Override
public void update(int id, double balance) {
//构建同构的sql语句,jdbcTemplate对象底层通过conn连接获得Ps对象执行同构sql语句
String updateSql = "update t_account set balance=? where id=?";
jdbcTemplate.update(updateSql, balance, id);
//如果使用Spring容器中数据源DataSource
//如果把dataSource注入dao层来直接使用,则需要注意下面几个点
try {
//一定不要这样拿conn 因为我们要保证service层开始事务和提交事务用的conn和dao层用到的conn是同一个对象
//Connection conn = dataSource.getConnection();//获取到conn
//一定要这样去拿conn,因为DataSourceUtils是spring提供的工具类
Connection conn = DataSourceUtils.getConnection(dataSource);
//
Statement stmt = conn.createStatement();
int id = account.getId();
String name = account.getName();
double balance = account.getBalance();
String sql = "insert into t_account(id,name,balance) values("+id+",'"+name+"',"+balance+")";
stmt.execute(sql);
stmt.close();
//不要关闭conn 因为这里一关闭conn,在service中就拿不到这个对象了
//conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
Spring配置文件
<!-- 读取这个资源文件 读完之后下面就可以用${key}来去文件中的value值了 -->
<!-- 这种方式是我们第一节学习的那种配置方式方式的简写 -->
<context:property-placeholder location="classpath:oracle.properties"/>
<!-- spring提供的一种数据源 -->
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${driver}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${user}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean>
<!-- 通过JdbcTemplate类的构造器,初始化dDataSource属性,jdbcTemplate对象通过dataSource获connection连接对象 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg index="0" ref="dataSource"></constructor-arg>
</bean>
<bean name="dao" class="com.briup.db.jdbc.JdbcTemplateDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
Test测试方法:获得Bean容器中的dao对象,进行数据库交互
@Test
public void jdbc_jdbcTemplate(){
try {
String path = "com/briup/db/jdbc/jdbcTemplate.xml";
ClassPathXmlApplicationContext container =
new ClassPathXmlApplicationContext(path);
AccountDao dao = (AccountDao) container.getBean("dao");
dao.update(1, 1100);
container.destroy();
}catch(Exception e) {
e.printStackTrace();
}
}
Mybatis:Mybatis框架是通过解析xml,通过SqlSessionFactoryBuilder的build方法创建出SqlSessionFactory对象,在通过openSession方法获取sqlSession对象,在通过getMapper方法动态获取映射接口的实现类对象,执行映射文件中的sql语句,完成与数据库的交互
Spring和Mybatis结合:需要导入相关jar包mybatis-spring-1.2.2.jar,Spring中通过SqlSessionFactoryBean创建出sqlSessionFactory对象注入到Bean容器中(有两种方式执行sql语句)
可以单独配置Mybatis-config.xml,也可以将Mybatis-config.xml整合到Spring配置文件中
Spring配置文件引入mybatis-config.xml文件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.briup.db" />
bean>
Spring配置文件中整合mybatis:不需要dao层实现类JDBCAccountDaoImpl,将sqlSessionFactory对象注入到Bean容器中,并扫描dao层接口AccountDao通过动态代理生成接口实现类对象,调用映射文件中的sql语句
AccountDao.java
public interface AccountDao {
//更新余额
void update(int accountId,double balance);
}
XxxMapper.xml
<mapper namespace="com.briup.db.AccountDao">
<update id="update">
update t_account
set
balance=#{arg1}
where id=#{arg0}
update>
mapper>
spring-mybatis.xml
<context:property-placeholder location="classpath:oracle.properties" />
<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${driver}value>
property>
<property name="url">
<value>${url}value>
property>
<property name="username">
<value>${user}value>
property>
<property name="password">
<value>${password}value>
property>
<property name="maxActive">
<value>80value>
property>
<property name="maxIdle">
<value>20value>
property>
<property name="maxWait">
<value>3000value>
property>
bean>
<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.briup.db">property>
<property name="configurationProperties">
<props>
<prop key="cacheEnabled">trueprop>
props>
property>
<property name="mapperLocations">
<list>
<value>classpath:com/briup/tran/mybatis/AccountMapper.xmlvalue>
list>
property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.briup.db" />
bean>