Spring-JdbcTemplate
- 它是 spring框架中提供的一個對象,是對原始 Jdbc API對象的簡單封裝。
1.需要的jar包:
在maven中導入jar
包座標如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
2.Spring簡單配置Template:
- 使用Spring內置的數據源
DriverManagerDataSource
。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/case01"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
- 測試:
//1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.獲取對象
JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.執行操作
jt.execute("insert into account(name,money)values('ATFWUS',888)");
//增
jt.update("insert into account(name,money)values(?,?)","ATFWUSS",8888);
//改
jt.update("update account set name=?,money=? where id=?","AT",8888,10);
//刪
jt.update("delete from account where id=?",18);
//查
List<Account> accounts = jt.query("select * from account where money > ?",
new BeanPropertyRowMapper<Account>(Account.class),8888);
Long count = jt.queryForObject("select count(*) from account where money > ?"
,Long.class,88);
3.JdbcDaoSupport :
- 在dao層若使用Spring配置的話,需要注入JdbcTemplate,如果我們使用讓dao層的類繼承
JdbcDaoSupport
,就可以把這些交給Spring處理,但是,一旦繼承此類,將無法再使用註解的方式去配置。 JdbcDaoSupport
源碼:
/**
* Convenient super class for JDBC-based data access objects.
*
* <p>Requires a {@link javax.sql.DataSource} to be set, providing a
* {@link org.springframework.jdbc.core.JdbcTemplate} based on it to
* subclasses through the {@link #getJdbcTemplate()} method.
*
* <p>This base class is mainly intended for JdbcTemplate usage but can
* also be used when working with a Connection directly or when using
* {@code org.springframework.jdbc.object} operation objects.
*
* @author Juergen Hoeller
* @since 28.07.2003
* @see #setDataSource
* @see #getJdbcTemplate
* @see org.springframework.jdbc.core.JdbcTemplate
*/
public abstract class JdbcDaoSupport extends DaoSupport {
@Nullable
private JdbcTemplate jdbcTemplate;
/**
* Set the JDBC DataSource to be used by this DAO.
*/
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
/**
* Create a JdbcTemplate for the given DataSource.
* Only invoked if populating the DAO with a DataSource reference!
* <p>Can be overridden in subclasses to provide a JdbcTemplate instance
* with different configuration, or a custom JdbcTemplate subclass.
* @param dataSource the JDBC DataSource to create a JdbcTemplate for
* @return the new JdbcTemplate instance
* @see #setDataSource
*/
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
/**
* Return the JDBC DataSource used by this DAO.
*/
@Nullable
public final DataSource getDataSource() {
return (this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null);
}
/**
* Set the JdbcTemplate for this DAO explicitly,
* as an alternative to specifying a DataSource.
*/
public final void setJdbcTemplate(@Nullable JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}
/**
* Return the JdbcTemplate for this DAO,
* pre-initialized with the DataSource or set explicitly.
*/
@Nullable
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
/**
* Initialize the template-based configuration of this DAO.
* Called after a new JdbcTemplate has been set, either directly
* or through a DataSource.
* <p>This implementation is empty. Subclasses may override this
* to configure further objects based on the JdbcTemplate.
* @see #getJdbcTemplate()
*/
protected void initTemplateConfig() {
}
@Override
protected void checkDaoConfig() {
if (this.jdbcTemplate == null) {
throw new IllegalArgumentException("'dataSource' or 'jdbcTemplate' is required");
}
}
/**
* Return the SQLExceptionTranslator of this DAO's JdbcTemplate,
* for translating SQLExceptions in custom JDBC access code.
* @see org.springframework.jdbc.core.JdbcTemplate#getExceptionTranslator()
*/
protected final SQLExceptionTranslator getExceptionTranslator() {
JdbcTemplate jdbcTemplate = getJdbcTemplate();
Assert.state(jdbcTemplate != null, "No JdbcTemplate set");
return jdbcTemplate.getExceptionTranslator();
}
/**
* Get a JDBC Connection, either from the current transaction or a new one.
* @return the JDBC Connection
* @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed
* @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
*/
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
DataSource dataSource = getDataSource();
Assert.state(dataSource != null, "No DataSource set");
return DataSourceUtils.getConnection(dataSource);
}
/**
* Close the given JDBC Connection, created via this DAO's DataSource,
* if it isn't bound to the thread.
* @param con Connection to close
* @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
*/
protected final void releaseConnection(Connection con) {
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
- dao層測試類:
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?"
,new BeanPropertyRowMapper<Account>(Account.class),accountId);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String accountName) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?"
,new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("結果不唯一");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?"
,account.getName(),account.getMoney(),account.getId());
}
}
Spring - 事務控制
- Spring中提供類一組用於事務控制的API。
1.API介紹:
-
PlatformTransactionManager
:此接口是 spring的事務管理器,它裏面提供了我們常用的操作事務的方法。-
TransactionStatus getTransaction(TransactionDefinition definition)
:獲取事務狀態信息。 -
void commit(TransactionStatus status)
:提交事務。 -
void rollback(TransactionStatus status)
:回滾事務。 -
實現類:
-
DataSourceTransactionManager
:使用 Spring JDBC或 iBatis 進行持久化數據時使用。 -
HibernateTransactionManager
:使用Hibernate版本進行持久化數據時使用 。
-
-
-
TransactionDefinition
:它是事務的定義信息對象。方法如下:String getName()
:獲取事務對象名稱。int getIsolationLevel()
:獲取事務隔離級別。int getPropagationBehavior()
:獲取事務傳播行爲。int getTimeout()
:獲取事務超時時間。默認爲-1
,即沒有超時限制,如果有,以秒設置。boolean isReadOnly()
:獲取事務是否只讀。
-
TransactionStatus
:此接口提供的是事務具體的運行狀態,方法如下:void flush()
:刷新事務。boolean hasSavapoint()
:獲取是否存在存儲點。boolean isCompleted()
:獲取事務是否完成。boolean isNewTransaction()
:獲取是否爲新事務。boolean isRollbackOnly()
:獲取事務是否回滾。void setRollbackOnly()
:設置事務回滾。
2.Spring事務控制-XML配置:
事務管理器配置:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
配置事務的通知:
-
tx:advice
:標籤配置事務通知。- 屬性
id
:給事務通知起一個唯一標識。 - 屬性
transaction-manager
:給事務通知提供一個事務管理器引用。
- 屬性
-
在aop中配置切入點表達式,並且建立切入點表達式和事務通知的對應關係。
<aop:config>
<!-- 配置切入點表達式-->
<aop:pointcut id="pt1" expression="execution(* com.atfwus.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入點表達式和事務通知的對應關係 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
-
配置事務的屬性,在事務的通知
tx:advice
標籤的內部使用<tx:attributes>
,<tx:method
:- 屬性
name
:指定方法名稱,可以使用通配符。 - 屬性
isolation
:用於指定事務的隔離級別。默認值是DEFAULT,表示使用數據庫的默認隔離級別。 - 屬性
propagation
:用於指定事務的傳播行爲。默認值是REQUIRED,表示一定會有事務,增刪改的選擇。查詢方法可以選擇SUPPORTS。 - 屬性
read-only
:用於指定事務是否只讀。只有查詢方法才能設置爲true。默認值是false,表示讀寫。 - 屬性
timeout
:用於指定事務的超時時間,默認值是-1,表示永不超時。如果指定了數值,以秒爲單位。 - 屬性
rollback-for
:用於指定一個異常,當產生該異常時,事務回滾,產生其他異常時,事務不回滾。沒有默認值。表示任何異常都回滾。 - 屬性
no-rollback-for
:用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時事務回滾。沒有默認值。表示任何異常都回滾。
- 屬性
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置業務層-->
<bean id="accountService" class="com.atfwus.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置持久層-->
<bean id="accountDao" class="com.atfwus.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/case02"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事務的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置aop-->
<aop:config>
<!-- 配置切入點表達式-->
<aop:pointcut id="pt1" expression="execution(* com.atfwus.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入點表達式和事務通知的對應關係 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
3.Spring事務控制-註解配置:
步驟:
- 配置事務管理器。
- 開啓spring對註解事務的支持。
- 在需要事務支持的地方使用
@Transactional
註解
開啓註解支持:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring創建容器時要掃描的包-->
<context:component-scan base-package="com.atfwus"></context:component-scan>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/case02"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 開啓spring對註解事務的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
普通註解與純註解:
- 普通註解
@Transactional
,屬性與上述事務屬性一致,如:@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
- 純註解:
@EnableTransactionManagement
,在配置類中,配置事務管理器。
ATFWUS --Writing By 2020–04-23