返回介绍

10.1 JDBC 方式下的事务使用示例

发布于 2025-04-22 22:09:16 字数 4670 浏览 0 评论 0 收藏

(1)创建数据表结构。

CREATE TABLE 'user' (

  'id' int(11) NOT NULL auto_increment,

  'name' varchar(255) default NULL,

  'age' int(11) default NULL,

  'sex' varchar(255) default NULL,

  PRIMARY KEY ('id')

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

(2)创建对应数据表的 PO。

public class User {

  private int id;

  private String name;

  private int age;

private String sex;

//省略 set/get 方法

}

(3)创建表与实体间的映射。

public class UserRowMapper implements RowMapper {

 @Override

  public Object mapRow(ResultSet set, int index) throws SQLException {

   User person = new User(set.getInt("id"), set.getString("name"), set

   .getInt("age"), set.getString("sex"));

   return person;

 }

}

(4)创建数据操作接口。

@Transactional(propagation=Propagation.REQUIRED)

public interface UserService {

  public void save(User user) throws Exception;

}

(5)创建数据操作接口实现类。

public class UserServiceImpl implements UserService {

  private JdbcTemplate jdbcTemplate;

 // 设置数据源

  public void setDataSource(DataSource dataSource) {

   this.jdbcTemplate = new JdbcTemplate(dataSource);

 }

  public void save(User user) throws Exception {

   jdbcTemplate.update("insert into user(name,age,sex)values(?,?,?)",

   new Object[] { user.getName(), user.getAge(),

   user.getSex() }, new int[] { java.sql.Types.VARCHAR,

   java.sql.Types.INTEGER, java.sql.Types.VARCHAR });

  //事务测试,加上这句代码则数据不会保存到数据库中

   throw new RuntimeException("aa");

 }

}

(6)创建 Spring 配置文件。

<?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: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-2.5.xsd

  http://www.Springframework.org/schema/context http://www.Springframework.

 org/schema/context/Spring-context-2.5.xsd

   http://www.Springframework.org/schema/tx http://www.Springframework.org/

  schema/tx/Spring-tx-2.5.xsd

 ">

  <tx:annotation-driven transaction-manager="transactionManager" />

   <bean id="transactionManager"

  class="org.Springframework.jdbc.datasource.DataSourceTransactionManager">

   <property name="dataSource" ref="dataSource" />

 </bean>

  <!--配置数据源 -->

  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

  destroy-method="close">

   <property name="driverClassName" value="com.mysql.jdbc.Driver" />

   <property name="url" value="jdbc:mysql://localhost:3306/lexueba" />

   <property name="username" value="root" />

   <property name="password" value="haojia0421xixi" />

   <!--连接池启动时的初始值 -->

   <property name="initialSize" value="1" />

   <!--连接池的最大值 -->

   <property name="maxActive" value="300" />

  <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减

  少到 maxIdle 为止 -->

   <property name="maxIdle" value="2" />

   <!--最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

   <property name="minIdle" value="1" />

 </bean>

  <!--配置业务 bean:PersonServiceBean -->

  <bean id="userService" class="service.UserServiceImpl">

   <!--向属性 dataSource 注入数据源 -->

   <property name="dataSource" ref="dataSource"></property>

 </bean>

</beans>

(7)测试。

public static void main(String[] args) throws Exception {

  ApplicationContext act = new ClassPathXmlApplicationContext("bean.xml");

  UserService userService = (UserService) act.getBean("userService");

  User user = new User();

 user.setName("张三 ccc");

 user.setAge(20);

 user.setSex("男");

 // 保存一条记录

 userService.save(user);

 }

}

上面的测试示例中,UserServiceImpl 类对接口 UserService 中的 save 函数的实现最后加入了一句抛出异常的代码:throw new RuntimeException("aa")。当注掉这段代码执行测试类,那么会看到数据被成功的保存到了数据库中,但是如果加入这段代码时再次运行测试类,发现此处的操作并不会将数据保存到数据库中。

注意 默认情况下 Spring 中的事务处理只对 RuntimeException 方法进行回滚,所以,如果此处将 RuntimeException 替换成普通的 Exception 不会产生回滚效果。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。