一.Spring jdbc概述
1.概述:
Spring JDBC是Spring所提供的持久層技術,他主要目的降低JDBC API的使用難度,以一種更直接、更簡潔的方式使用JDBC API,
2.作用:
Spring的JDBC模塊負責資料庫資源和錯誤處理,大大簡化了開發人員對資料庫的操作,
3.包:
- core:核心包,包含了JDBC的核心功能,例如jdbcTemplate類
- datasource:資料源包
- object:物件包
- support:支持包,是core包和object包的支持類,
二.Spring jdbc的配置
針對mysql資料庫,有以下四種配置:
1.使用org.springframework.jdbc.datasource.DriverManagerDataSource
使用 DriverManagerDataSource建立連接是只要有連接就新建一個connection,根本沒有連接池的作用,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- spring管理jdbc和資料庫連接池-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="url" value="jdbc:mysql:///shop"></property>
</bean>
<!-- spring管理jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
2.使用org.apache.commons.dbcp.BasicDataSource
需要下載的jar包:commons-dbcp.jar,commons-pool.jar
說明:這是一種推薦說明的資料源配置方式,它真正使用了連接池技術
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- spring管理dbcp資料庫連接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="url" value="jdbc:mysql:///shop"></property>
<property name="maxActive" value="20"></property>
<property name="maxIdle" value="5"></property>
<property name="minIdle" value="2"></property>
<property name="maxWait" value="10000"></property>
</bean>
<!-- spring管理jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
3.spring管理c3p0資料庫連接池
注意:這種方法中用了$(username)之后好像會取當前計算機用戶名來連接資料庫,將db.properties中的username改成user就可以了,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- spring管理c3p0資料庫連接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///shop"></property>
<property name="password" value="root"></property>
<property name="user" value="root"></property>
</bean>
<!-- spring管理jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
4. 使用hibernate資料源
需要hiberante核心jar包,
目前三大框架較流行,spring一般與hiberante做搭檔,資料庫連接方式寫在hiberante的組態檔中,在spring管理hibernate中的組態檔中,直接讀取hibernate核心組態檔即可,
[html]
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocations">
<list>
<value>classpath:com/config/hibernate.cfg.xml</value>
</list>
</property>
<property name="mappingLocations">
<!-- 所有的物體類映射檔案 -->
<list>
<value>classpath:com/hibernate/hbm.xml</value>
</list>
</property>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocations">
<list>
<value>classpath:com/config/hibernate.cfg.xml</value>
</list>
</property>
<property name="mappingLocations">
<!-- 所有的物體類映射檔案 -->
<list>
<value>classpath:com/hibernate/hbm.xml</value>
</list>
</property>
三.jdbcTemplate
1.引入
Spring對資料庫的操作在jdbc上面做了深層次的封裝,使用Spring的注入功能,可以吧DataSource注冊到jdbcTemplate中
2.jdbcTemplate更新資料庫的常用方法
- update(更新資料,即資料的增刪改)
- batchUpdate(批量更新資料庫)
- queryForObject(查詢單行)
- query(查詢多行)
- queryForObject(查詢單值)
3.資料庫連接池的優點
- 資源重用,避免頻繁創建
- 更快的系統反應速度
- 實作某一應用最大可用資料庫連接數的限制避免某一應用獨占所有資源
- 統一的連接管理,避免資料庫連接池鏈接泄露
4.Spring中實作jdbcTemplate對資料庫操作
(1).匯入jar包
(2).src下創建屬性組態檔db.properties
driverClass=com.mysql.jdbc.Driver
#url=jdbc:mysql://localhost:3306/shop
url=jdbc:mysql://localhost:3306/shop
#username=root
user=root
password=root
(3).配置xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- 引入工程中src下的db.properties檔案1-->
<!-- 1 可以 <property name="location" value="db.properties"></property>-->
<!-- 2 不可以<property name="location" value="classpath*:db.properties"></property>-->
<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->
<!-- <property name="location" value="classpath:db.properties"></property>-->
<!-- </bean>-->
<!-- 引入工程中src下的db.properties檔案2-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- spring管理c3p0資料庫連接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="password" value="${password}"></property>
<property name="user" value="${user}"></property>
</bean>
<!-- spring管理jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
bean類:
package com.it.spring.jdbc;
public class Account {
private Integer id;
private String name;
private Double money;
public Account() {
}
public Account(Integer id, String name, Double money) {
this.id = id;
this.name = name;
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
測驗類
package com.it.spring.jdbc;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJDBCTest1 {
@Resource
JdbcTemplate jdbcTemplate;
/*由于jdbcTemplate在內部通過PreparedStatament執行SQL陳述句,所有可以系結引數的SQL陳述句,每個"?"占位符可以接受一個引數*/
@Test
public void addAccount(){
jdbcTemplate.update("insert into account(id,name,money)values(?,?,?)",5,"admin1",9100L);
System.out.println("--------操作成功!-----------");
}
@Test
public void updateAccount(){
jdbcTemplate.update("update account set name=?,money=? where id=?","wwe",19100L,5);
System.out.println("--------操作成功!-----------");
}
@Test
public void delAccount(){
jdbcTemplate.update("delete from account where id=?",5);
System.out.println("--------操作成功!-----------");
}
//?查詢某個屬性
@Test
public void findNameAccount(){
String name = jdbcTemplate.queryForObject("select name from account where id=?",String.class,4);
System.out.println("name-->"+name);
System.out.println("--------操作成功!-----------");
}
//?查詢某個屬性
@Test
public void countAccount(){
Long count = jdbcTemplate.queryForObject("select count(*) from account",Long.class);
System.out.println("count-->"+count);
System.out.println("--------操作成功!-----------");
}
//查詢回傳物件或集合
@Test
public void findAccountById(){
Account account = jdbcTemplate.queryForObject("select * from account where id=?",new MyRowMapper(),4);
if(account!=null){
System.out.println(account);
}
}
@Test
public void queryAllAccount(){
List<Account> accounts = jdbcTemplate.query("select * from account",new MyRowMapper());
for (Account account :accounts) {
System.out.println(account);
}
}
//定義內部類
class MyRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setMoney(resultSet.getDouble("money"));
account.setName(resultSet.getString("name"));
return account;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/137019.html
標籤:python
下一篇:Oracle編程( 其三)
