Spring JDBC与事务管理

tech2025-07-25  10

数据库配置中URL:

value="jdbc:mysql://localhost:3306/imooc?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF8"/>

applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--数据源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/imooc?useUnicode=true&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC&amp;characterEncoding=UTF8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--JdbcTemplate提供数据库的CRUD的API--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="employeeDao" class="com.imooc.spring.jdbc.dao.EmployeeDao"> <!--为Dao注入Template对象--> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> </beans>

按Id查询数据语句:

public Employee findById(Integer eno) { String sql = "select * from employee where eno=?"; Employee employee = jdbcTemplate.queryForObject(sql, new Object[]{eno}, new BeanPropertyRowMapper<Employee>(Employee.class)); return employee; }

jdbcTemplate.queryObject :查询单条数据 jdbcTemplate.query:查询复合数据

JdbcTemplate实现写入操作

EmployeeDao中一定要记得生成jdbcTemplate的set和get方法,否则配置文件中会报错:

Spring编程式事务

Spring声明式事务

声明式事务全部在配置文件中设置:

<!--1.事务管理器,用于创建事务/提交/回滚--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--2.事务通知配置,决定哪些方法使用事务,哪些方法不使用事务--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--propagation="REQUIRED" 代表需要使用事务--> <!--目标方法名为batchImport时,启用声明式事务,成功提交,运行时异常回滚--> <tx:method name="batchImport" propagation="REQUIRED"/> <!--设置所有以find开头的都不使用事务--> <tx:method name="find*" propagation="NOT_SUPPORTED" read-only="true"/> <!--其他所有的方法都使用事务--> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--定义声明式事务的作用范围--> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.imooc..*Service.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> </aop:config>

事务传播行为(面试时经常被问到)

使用注解声明事务的配置文件: 关闭方法的事务:

最新回复(0)