Java中的数据库事务
简介
简介及代码,补入这篇博客。
Java中的应用
通过代码的方式来实现数据库事务
补入这篇博客
通过注解的方式来实现数据库事务
此处有两点需要注意:
- 需要将一个数据库事务的语句都放在一个方法中,以此来判断哪些代码归于一个事务。
- 在方法声明时添加注解,而不是放在方法调用处。
以下各注解的含义,详见这篇博客。
@Transactional(propagation = Propagation.REQUIRED)
使用此注解进行声明的方法,会将自己加入在调用此方法处的外层方法的事务中,如果外层方法均未添加事务,则为此方法创建一个事务,来容纳该方法。
@Transactional(propagation = Propagation.SUPPORTS )
使用此注解进行声明的方法,如果当前有事务则加入,如果没有事务则(不用事务)正常执行。
@Transactional(propagation = Propagation.REQUIRES_NEW)
使用此注解进行声明的方法,会为自身建立一个新事务,并挂起当前事务(如果有事务的话),待新事务执行完毕后再唤醒当前事务。该从此注解继续补完该博客。
JEECG中使用数据库事务
在生成的service文件中,添加方法声明
public interface PaperfileServiceI extends CommonService{
public void delete(PaperfileEntity entity) throws Exception;
public Serializable save(PaperfileEntity entity) throws Exception;
public void saveOrUpdate(PaperfileEntity entity) throws Exception;
//自定义的抽象方法,用于添加文件表和记录表
public void deliveryAndRecord(PaperfileEntity entity,DeliveryrecordEntity deliveryrecordEntity) throws Exception;
}
在service的接口实现类中完成代码
在继承自service接口的刚才定义好的方法中,添加业务逻辑的代码,并添加@Transactional
注解,如下图所示。
@Transactional
@Override
public void deliveryAndRecord(PaperfileEntity entity,DeliveryrecordEntity deliveryrecordEntity) throws Exception {
// TODO Auto-generated method stub
save(entity);
save(deliveryrecordEntity);
}
注意,如果是在“PaperfileServiceImpl”文件中 存储“PaperfileEntity” ,那么直接使用代码生成的save(PaperfileEntity Entity)方法,如下图红框所示。
如果还需要在PaperfileServiceImpl中添加其他类对象,如上图中的“deliveryrecordEntity”投递记录,则调用使用泛型作为传入参数的save(T t)方法来存储投递记录,如下图所示。