spring操做數據庫(JDBC)

spring操做數據庫(JDBC)概述

        spring爲了簡化JDBC開發操做,避免一下常見錯誤,提供了一個類JdbcTemplate,使用這個類前須要傳入一個數據庫鏈接池(BasicDataSource對象)。因此在配置JdbcTemplate前,須要配置數據庫鏈接池BasicDataSource。html

配置文件beans.xml配置步驟

第一步:配置數據庫鏈接池(beans.xml)

參考代碼以下:java

<!-- 鏈接池基本配置信息 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;characterEncoding=utf8"></property>
	<property name="username" value="root"></property>
	<property name="password" value="liuxin950326"></property>
	
	<!-- 鏈接池啓動時的初始值 -->
	<property name="initialSize" value="10"></property>
	<!-- 鏈接池的最大值 -->
	<property name="maxActive" value="80"></property>
	<!-- 最大空閒值.通過一個高峯時間,鏈接池可將已用不到鏈接慢慢釋放一部分,一直減小到maxIdle爲止 -->
	<property name="maxIdle" value="5"></property>
	<property name="minIdle" value="2"></property>
</bean>

第二步:配置JDBC模板JdbcTemplate類(beans.xml)

參考代碼以下:mysql

<!-- 配置JDBC模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<property name="dataSource" ref="dataSource"></property>
</bean>

第三步:配置Dao層(beanx,xml)

<!-- 配置Dao層 -->
<bean id="bankAccountDao" class="www.enfp.lx_03_jdbc.lx_02_crud.BankAccountDaoImpl">
	<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

JdbcTemplate操做數據庫(增刪改查)

1.增

public int update(String sql,
                  Object... args)
           throws DataAccessException

Description copied from interfaceJdbcOperationsspring

Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments.sql

Specified by:數據庫

update in interface JdbcOperationsapache

Parameters:api

sql - SQL containing bind parametersoracle

args - arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also contain SqlParameterValue objects which indicate not only the argument value but also the SQL type and optionally the scaleapp

Returns:

the number of rows affected

Throws:

DataAccessException - if there is any problem issuing the update

參考代碼以下:

//增
{
	String sql = "insert into bankaccount(accountname,balance) value(?,?)";
	Object[] args = { account.getAccountName(), account.getBalance() };
	this.getJdbcTemplate().update(sql, args);
}

//刪
{
	String sql = "delete from bankaccount where accountname=?";
	Object[] args = { accountName };
	this.getJdbcTemplate().update(sql, args);

}

//改
{
	String sql = "update bankaccount set balance=? where accountname=?";
	Object[] args = { account.getBalance(), account.getAccountName() };
	this.getJdbcTemplate().update(sql, args);
}

2.查

(1).查詢多條記錄

public <T> List<T> query(String sql,
                         RowMapper<T> rowMapper)
                  throws DataAccessException

Description copied from interfaceJdbcOperations

Execute a query given static SQL, mapping each row to a Java object via a RowMapper.

Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded query method with null as argument array.

Specified by:

query in interface JdbcOperations

Parameters:

sql - SQL query to execute

rowMapper - object that will map one object per row

Returns:

the result List, containing mapped objects

Throws:

DataAccessException - if there is any problem executing the query

See Also:

JdbcOperations.query(String, Object[], RowMapper)

注意:RowMapper是一個接口,在JdbcTemplate中用於映射查詢的結果集ResultSet中的每一行,實際使用中必須實現這個接口中的mapRow(ResultSet rs, int rowNum)方法。

T mapRow(ResultSet rs,
         int rowNum)
  throws SQLException

Implementations must implement this method to map each row of data in the ResultSet. This method should not call next()on the ResultSet; it is only supposed to map values of the current row.

Parameters:

rs - the ResultSet to map (pre-initialized for the current row)

rowNum - the number of the current row

Returns:

the result object for the current row

Throws:

SQLException - if a SQLException is encountered getting column values (that is, there's no need to catch SQLException)

參考代碼以下:

String sql = "select accountname,balance from bankaccount";
RowMapper rowMapper = new RowMapper()
{

	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException
	{
		BankAccount account = new BankAccount();
		account.setAccountName(rs.getString("accountname"));
		account.setBalance(rs.getDouble("balance"));
		return account;
	}

};
List<BankAccount> bankAccountList = this.getJdbcTemplate().query(sql,rowMapper);

(2).查詢單條記錄

public <T> T queryForObject(String sql,
                            Object[] args,
                            RowMapper<T> rowMapper)
                     throws DataAccessException

Description copied from interfaceJdbcOperations

Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a Java object via a RowMapper.

Specified by:

queryForObject in interface JdbcOperations

Parameters:

sql - SQL query to execute

args - arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also contain SqlParameterValue objects which indicate not only the argument value but also the SQL type and optionally the scale

rowMapper - object that will map one object per row

Returns:

the single mapped object

Throws:

IncorrectResultSizeDataAccessException - if the query does not return exactly one row

DataAccessException - if the query fails

參考代碼以下:

String sql = "select accountname,balance from bankaccount where accountname=?";
Object[] args = { accountName };
RowMapper rowMapper = new RowMapper()
{

	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException
	{
		BankAccount account = new BankAccount();
		account.setAccountName(rs.getString("accountname"));
		account.setBalance(rs.getDouble("balance"));
		return account;
	}

};
BankAccount account = this.getJdbcTemplate().queryForObject(sql, rowMapper, args);

案例:spring實現數據庫增刪改查

1.beans.xml配置文件

參考代碼以下:beans.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-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- 鏈接池基本配置信息 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;characterEncoding=utf8"></property>
		<property name="username" value="root"></property>
		<property name="password" value="liuxin950326"></property>
		
		<!-- 鏈接池啓動時的初始值 -->
		<property name="initialSize" value="10"></property>
		<!-- 鏈接池的最大值 -->
		<property name="maxActive" value="80"></property>
		<!-- 最大空閒值.通過一個高峯時間,鏈接池可將已用不到鏈接慢慢釋放一部分,一直減小到maxIdle爲止 -->
		<property name="maxIdle" value="5"></property>
		<property name="minIdle" value="2"></property>
	</bean>
	
	
	<!-- 配置JDBC模板 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	
	<!-- 配置Dao層 -->
	<bean id="bankAccountDao" class="www.enfp.lx_03_jdbc.lx_02_crud.BankAccountDaoImpl">
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
	
	
</beans>

2.pojo(銀行帳戶)

參考代碼以下:BankAccount.java

package www.enfp.lx_03_jdbc.lx_02_crud;

public class BankAccount
{
	private String accountName = null;
	private double balance = 0;

	@Override
	public String toString()
	{
		return "accountName:" + this.accountName + "\t balance:" + this.balance;
	}

	public String getAccountName()
	{
		return accountName;
	}

	public void setAccountName(String accountName)
	{
		this.accountName = accountName;
	}

	public double getBalance()
	{
		return balance;
	}

	public void setBalance(double balance)
	{
		this.balance = balance;
	}

	public BankAccount(String accountName, double balance)
	{
		super();
		this.accountName = accountName;
		this.balance = balance;
	}

	public BankAccount()
	{
		super();
	}

}

3.Dao類

參考代碼以下:

IBankAccountDao.java接口

package www.enfp.lx_03_jdbc.lx_02_crud;

import java.util.List;

public interface IBankAccountDao
{
	public void addBankAccount(BankAccount account);// 增

	public void deleteBankAccount(String accountName);// 刪

	public void updateBankAccount(BankAccount account);// 改

	// 查
	public List<BankAccount> queryAllBankAccount();

	public BankAccount queryBankAccountByAccountName(String accountName);

}

BankAccountDaoImpl.java類

package www.enfp.lx_03_jdbc.lx_02_crud;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class BankAccountDaoImpl implements IBankAccountDao
{
	private JdbcTemplate jdbcTemplate = null;

	public JdbcTemplate getJdbcTemplate()
	{
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
	{
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void addBankAccount(BankAccount account)
	{
		String sql = "insert into bankaccount(accountname,balance) value(?,?)";
		Object[] args = { account.getAccountName(), account.getBalance() };
		this.getJdbcTemplate().update(sql, args);
	}

	@Override
	public void deleteBankAccount(String accountName)
	{
		String sql = "delete from bankaccount where accountname=?";
		Object[] args = { accountName };
		this.getJdbcTemplate().update(sql, args);

	}

	@Override
	public void updateBankAccount(BankAccount account)
	{
		String sql = "update bankaccount set balance=? where accountname=?";
		Object[] args = { account.getBalance(), account.getAccountName() };
		this.getJdbcTemplate().update(sql, args);
	}

	@Override
	public List<BankAccount> queryAllBankAccount()
	{
		String sql = "select accountname,balance from bankaccount";
		RowMapper rowMapper = new RowMapper()
		{

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException
			{
				BankAccount account = new BankAccount();
				account.setAccountName(rs.getString("accountname"));
				account.setBalance(rs.getDouble("balance"));
				return account;
			}

		};
		List<BankAccount> bankAccountList = this.getJdbcTemplate().query(sql,
				rowMapper);
		return bankAccountList;
	}

	@Override
	public BankAccount queryBankAccountByAccountName(String accountName)
	{
		String sql = "select accountname,balance from bankaccount where accountname=?";
		Object[] args = { accountName };
		RowMapper rowMapper = new RowMapper()
		{

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException
			{
				BankAccount account = new BankAccount();
				account.setAccountName(rs.getString("accountname"));
				account.setBalance(rs.getDouble("balance"));
				return account;
			}

		};
		BankAccount account = this.getJdbcTemplate().queryForObject(sql,
				rowMapper, args);
		return account;
	}

}

4.測試

參考代碼以下:test.java

package www.enfp.lx_03_jdbc.lx_02_crud;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test
{

	public static void main(String[] args)
	{
		ApplicationContext container = new ClassPathXmlApplicationContext(
				"www/enfp/lx_03_jdbc/lx_02_crud/beans.xml");

		IBankAccountDao accountDao = (IBankAccountDao) container
				.getBean("bankAccountDao");
		// 添加
		// accountDao.addBankAccount(new BankAccount("zhangsan", 1000));
		// accountDao.addBankAccount(new BankAccount("lisi", 1000));
		// accountDao.addBankAccount(new BankAccount("wangxiaojian", 1000));

		// 刪除
		// accountDao.deleteBankAccount("zhangsan");

		// 修改
		// accountDao.updateBankAccount(new BankAccount("lisi", 2000));

		// 按accountName查詢
		// System.out.println(accountDao.queryBankAccountByAccountName("lisi"));

		// 查詢全部
		for (BankAccount account : accountDao.queryAllBankAccount())
		{
			System.out.println(account);
		}

	}
}
相關文章
相關標籤/搜索