| 77 | | * pg 里没有rollback 语句,不会自动rollback ,需要应用里触发异常。 |
| | 77 | * pg 里没有rollback 语句,不会自动rollback ,需要应用里触发异常。 |
| | 78 | {{{ |
| | 79 | 1.使用JPA,方法声明为@Transactional自动回滚 |
| | 80 | 2.使用JPA,手动方式进行回滚 |
| | 81 | EntityManagerFactory emf = ((EntityManagerFactory)EnvUtils.getEnv().getApplicationContext().getBean("entityManagerFactory")); |
| | 82 | EntityManager em = emf.createEntityManager(); |
| | 83 | EntityTransaction et = em.getTransaction(); |
| | 84 | try { |
| | 85 | et.begin();//事务开始 |
| | 86 | em.createNativeQuery(sql).executeUpdate(); |
| | 87 | em.createNativeQuery(sql).executeUpdate(); |
| | 88 | et.commit(); |
| | 89 | } catch (Exception e) { |
| | 90 | et.rollback(); |
| | 91 | } |
| | 92 | 3.使用JDBC |
| | 93 | DataSourceTransactionManager tm = new DataSourceTransactionManager(((DataSource) EnvUtils.getEnv().getApplicationContext().getBean("dataSource"))); |
| | 94 | TransactionTemplate tt = new TransactionTemplate(tm); |
| | 95 | final JdbcTemplate jt = new JdbcTemplate(((DataSource) EnvUtils.getEnv().getApplicationContext().getBean("dataSource"))); |
| | 96 | tt.execute(new TransactionCallback() { |
| | 97 | public Object doInTransaction(TransactionStatus ts) { |
| | 98 | String sql = "update ent_faq set title = '压力山大' where id = 1"; |
| | 99 | jt.execute(sql); |
| | 100 | sql = "update ent_faq set title = title || '困死我了' where id = 3"; |
| | 101 | jt.execute(sql); |
| | 102 | return null; |
| | 103 | } |
| | 104 | }); |
| | 105 | }}} |