Spring?JDBC使用步驟和事務(wù)管理
Spring JDBC是Spring框架用來處理關(guān)系型數(shù)據(jù)庫的模塊,對JDBC的API進(jìn)行了封裝。
Spring JDBC的核心類為JdbcTemplate,提供數(shù)據(jù)CRUD方法
Spring JDBC使用步驟
1.Maven工程引入依賴spring-jdbc
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>2.xml中配置DataSource數(shù)據(jù)源
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>3.xml中定義JdbcTemplate Bean,讓IoC容器初始化時自動實(shí)例化
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>4.在需要增刪改查的Dao中,持有JdbcTemplate屬性,并設(shè)置getter和setter方法,然后在對應(yīng)的業(yè)務(wù)處理方法中,調(diào)用JdbcTemplate的指定方法。
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
//數(shù)據(jù)查詢方法
public Employee findById(Integer eno){
String sql="select * from employee where eno = ?";
Employee employee = jdbcTemplate.queryForObject(sql,new Object[]{eno},new BeanPropertyRowMapper<>(Employee.class));
return employee;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}5.在xml中為Dao類注入JdbcTemplate對象
<bean id="employeeDao" class="spring.jdbc.dao.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>JdbcTemplate數(shù)據(jù)查詢方法:

例:
public List<Employee> findByDname(String dname){
String sql = "select * from employee where dname = ?";
List<Employee> list = jdbcTemplate.query(sql,new Object[]{dname},new BeanPropertyRowMapper<>(Employee.class));
return list;
}
public List<Map<String, Object>> findMapByDname(String dname){
String sql = "select eno as empno,salary as s from employee where dname = ?";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, new Object[]{dname});
return maps;
}JdbcTemplate數(shù)據(jù)寫入方法:

例:
public void insert(Employee employee){
String sql = "insert into employee(eno,ename,salary,dname) values(?,?,?,?)";
//利用update方法實(shí)現(xiàn)數(shù)據(jù)寫入操作
jdbcTemplate.update(sql,new Object[]{
employee.getEno(),employee.getEname(),employee.getSalary(), employee.getDname()
});
}
public int update(Employee employee){
String sql = "update employee set ename=?,salary=?,dname=? where eno=?";
//利用update方法實(shí)現(xiàn)數(shù)據(jù)更新操作
int count = jdbcTemplate.update(sql,new Object[]{
employee.getEname(),employee.getSalary(), employee.getDname(),employee.getEno()
});
return count;
}
public int delete(Integer eno){
String sql = "delete from employee where eno = ?";
//利用update方法實(shí)現(xiàn)數(shù)據(jù)刪除操作
return jdbcTemplate.update(sql,new Object[]{eno});
}Spring事務(wù)管理
事務(wù)是一種可靠、一致的方式,是訪問操作數(shù)據(jù)庫的程序單元,事務(wù)要么把事情做完,要么不做,不會做一半停止。
事務(wù)依賴數(shù)據(jù)庫實(shí)現(xiàn),MySQL通過事務(wù)區(qū)作為數(shù)據(jù)緩沖地帶。
編程式事務(wù)
通過代碼手動提交回滾事務(wù)的事務(wù)控制方式。
SpringJDBC通過TransactionManager事務(wù)管理器實(shí)現(xiàn)事務(wù)控制。
TransactionManager事務(wù)管理器提供commit、rollback方法進(jìn)行事務(wù)提交和回滾。
編程式事務(wù)使用步驟:
1.配置事務(wù)管理器
<!-- 事務(wù)管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>2.在需要開啟事務(wù)的業(yè)務(wù)類中,持有事務(wù)管理器屬性,并設(shè)置getter和setter方法
private DataSourceTransactionManager transactionManager;
public DataSourceTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(DataSourceTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}3.配置事務(wù)管理器對象注入
<bean id="employeeService" class="spring.jdbc.service.EmployeeService">
<property name="employeeDao" ref="employeeDao"></property>
<property name="transactionManager" ref="transactionManager"></property>
</bean>定義事務(wù)默認(rèn)的標(biāo)準(zhǔn)配置,開啟事務(wù),進(jìn)行事務(wù)管理

聲明式事務(wù)
在不修改代碼的情況下通過配置的形式實(shí)現(xiàn)事務(wù)控制,本質(zhì)就是AOP環(huán)繞通知。
聲明式事務(wù)的觸發(fā)時機(jī):
- 當(dāng)目標(biāo)方法執(zhí)行成功時,自動提交事務(wù)
- 當(dāng)目標(biāo)方法拋出
運(yùn)行時異常時,自動事務(wù)回滾
聲明式事務(wù)配置過程:
1.需要添加AOP依賴
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>2,添加tx和aop命名空間

3.配置TransactionManager事務(wù)管理器
<!-- 事務(wù)管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>4.配置事務(wù)通知與事務(wù)屬性
<!--事務(wù)通知配置,決定哪些方法使用事務(wù),哪些方法不使用事務(wù)-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--propagation事務(wù)傳播行為-->
<!--當(dāng)目標(biāo)方法名為batchImport時,啟用聲明式事務(wù),運(yùn)行成功提交事務(wù),運(yùn)行時異常回滾-->
<!--目標(biāo)方法允許使用通配符*-->
<tx:method name="batchImport" propagation="REQUIRED"/>
<!--設(shè)置所有findXXX方法不啟用事務(wù)-->
<tx:method name="find*" propagation="NOT_SUPPORTED" read-only="true"/>
<tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true"/>
<!--設(shè)置其他方法不啟用事務(wù)-->
<tx:method name="*" propagation="NOT_SUPPORTED" read-only="true"/>
</tx:attributes>
</tx:advice>5.為事務(wù)通知綁定PointCut切點(diǎn)
<!--定義聲明式事務(wù)的作用范圍-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* spring.jdbc..*Service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>事務(wù)傳播行為propagation
多個擁有事務(wù)的方法在嵌套調(diào)用時的事務(wù)控制方式。

注解配置聲明式事務(wù)
xml配置
<context:component-scan base-package="spring.jdbc"/>
<!--數(shù)據(jù)源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--事務(wù)管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--啟用注解形式聲明式事務(wù)-->
<tx:annotation-driven transaction-manager="transactionManager"/>2.分層添加組件注解,實(shí)例化對象
@Repository
public class EmployeeDao {
@Resource
private JdbcTemplate jdbcTemplate;
...@Service
public class EmployeeService {
@Resource
private EmployeeDao employeeDao;
...3.需要開啟事務(wù)的類添加@Transactional注解,可以設(shè)置事務(wù)傳播行為,如@Transactional(propagation = Propagation.REQUIRED

或者為方法單獨(dú)設(shè)置事務(wù)管理方式,程序執(zhí)行時優(yōu)先應(yīng)用方法上的配置

到此這篇關(guān)于Spring JDBC使用步驟和事務(wù)管理的文章就介紹到這了,更多相關(guān)Spring事務(wù)管理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring擴(kuò)展BeanFactoryPostProcessor使用技巧詳解
這篇文章主要為大家介紹了Spring擴(kuò)展BeanFactoryPostProcessor使用技巧詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
SpringBoot?+?MyBatis-Plus構(gòu)建樹形結(jié)構(gòu)的幾種方式
在實(shí)際開發(fā)中,很多數(shù)據(jù)都是樹形結(jié)構(gòu),本文主要介紹了SpringBoot?+?MyBatis-Plus構(gòu)建樹形結(jié)構(gòu)的幾種方式,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
Spring中的@ConditionalOnProperty注解詳解
這篇文章主要介紹了Spring中的@ConditionalOnProperty注解詳解,常見的@Conditionalxxx開頭的注解我們稱之為條件注解,常見的條件注解有,簡單來講,一般是在配置類上或者是@Bean修飾的方法上,添加此注解表示一個類是否要被Spring上下文加載,需要的朋友可以參考下2024-01-01
Java中Byte數(shù)組與InputStream相互轉(zhuǎn)換實(shí)現(xiàn)方式
在Java中,byte數(shù)組(byte[])和InputStream之間的相互轉(zhuǎn)換是常見的IO操作,下面通過本文給大家分享Java中Byte數(shù)組與InputStream相互轉(zhuǎn)換方式,感興趣的朋友跟隨小編一起看看吧2025-09-09
springboot?如何解決yml沒有spring的小葉子標(biāo)志問題
這篇文章主要介紹了springboot?如何解決yml沒有spring的小葉子標(biāo)志問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
java實(shí)現(xiàn)飯店點(diǎn)菜系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)飯店點(diǎn)菜系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01

