今天我们说一下,如何开启事务。
之前,我们在JpaConfiguration中配置了事务开启。
详见:https://blog.csdn.net/hanjun0612/article/details/105239557
如果没有开启事务,会报错:Executing an update/delete query
一,Dao事务
其中有这一段,代表了Dao事务开启。
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
所以,如果是Dao的方法,
我们只需要加上:@Transactional和@Modifying就可以了
@Repository public interface AccountDao extends JpaRepository<Account,Integer> { @Transactional @Modifying @Query(value="update test_account set balance=balance-:balance where name=:name",nativeQuery=true) void update(@Param(value = "name")String name,@Param(value = "balance")Double balance); }
二,Service事务
如果你是Service事务的话,需要在Application启动里添加 @EnableTransactionManagement
@SpringBootApplication(scanBasePackages = {"com.test"}) @EnableEurekaClient @EnableTransactionManagement public class Service1Application { public static void main(String[] args) { SpringApplication.run(Service1Application.class, args); } }
Service的调用
这里要注意:@Transactional,不指定rollbackFor的话,
默认只是回滚RuntimeException的异常。
那么Exception的异常就不会回滚了。
package com.test.service; import com.test.dao.AccountDao; import com.test.model.Account; import org.hibernate.SQLQuery; import org.hibernate.transform.Transformers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.Transient; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Tyler * @date 2020/3/31 */ @Service("accountService") public class AccountServiceImpl implements AccountService{ @PersistenceContext EntityManager em; @Transactional(rollbackFor = Exception.class) public void Update(Account entity) throws Exception { String sql = "update test_account set balance=balance+:balance where name=:name"; Map<String, Object> params = new HashMap<String, Object>(); params.put("balance",entity.getBalance()); params.put("name",entity.getName()); Query query = em.createNativeQuery(sql); for (Map.Entry<String, Object> entry : params.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); query.executeUpdate(); //throw new Exception("hello"); } }
具体看你,是哪里控制事务的,就哪里开启。