下面列出了org.springframework.transaction.annotation.Isolation#READ_COMMITTED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates or updates an artist.
*
* @param artist The artist to create/update.
*/
@Transactional(isolation = Isolation.READ_COMMITTED)
public void createOrUpdateArtist(Artist artist) {
String sql = "update artist set " +
"cover_art_path=?," +
"album_count=?," +
"last_scanned=?," +
"present=?," +
"folder_id=? " +
"where name=?";
int n = update(sql, artist.getCoverArtPath(), artist.getAlbumCount(), artist.getLastScanned(), artist.isPresent(), artist.getFolderId(), artist.getName());
if (n == 0) {
update("insert into artist (" + INSERT_COLUMNS + ") values (" + questionMarks(INSERT_COLUMNS) + ")",
artist.getName(), artist.getCoverArtPath(), artist.getAlbumCount(), artist.getLastScanned(), artist.isPresent(), artist.getFolderId());
}
int id = queryForInt("select id from artist where name=?", null, artist.getName());
artist.setId(id);
}
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
@SuppressWarnings("unchecked")
public int countByUK(T object) throws ServiceException, Exception {
if (object==null || !(object instanceof BaseValueObj) ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
int count=0;
Class<E> entityObjectClass=GenericsUtils.getSuperClassGenricType(getClass(), 1);
E entityObject=entityObjectClass.newInstance();
try {
this.doMapper(object, entityObject, this.getMapperIdVo2Po());
count=this.getBaseDataAccessObject().countByUK(entityObject);
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
/**
* Transactional标记保证query和update使用的是同一连接
* 事务隔离级别应该为READ_COMMITTED,Spring默认是DEFAULT(取决于底层使用的数据库,mysql的默认隔离级别为REPEATABLE_READ)
* <p>
* 如果是REPEATABLE_READ,那么在本次事务中循环调用tinyIdInfoDAO.queryByBizType(bizType)获取的结果是没有变化的,也就是查询不到别的事务提交的内容
* 所以多次调用tinyIdInfoDAO.updateMaxId也就不会成功
*
* @param bizType
* @return
*/
@Override
@Transactional(isolation = Isolation.READ_COMMITTED)
public SegmentId getNextSegmentId(String bizType) {
// 获取nextTinyId的时候,有可能存在version冲突,需要重试
for (int i = 0; i < Constants.RETRY; i++) {
TinyIdInfo tinyIdInfo = tinyIdInfoDAO.queryByBizType(bizType);
if (tinyIdInfo == null) {
throw new TinyIdSysException("can not find biztype:" + bizType);
}
Long newMaxId = tinyIdInfo.getMaxId() + tinyIdInfo.getStep();
Long oldMaxId = tinyIdInfo.getMaxId();
int row = tinyIdInfoDAO.updateMaxId(tinyIdInfo.getId(), newMaxId, oldMaxId, tinyIdInfo.getVersion(),
tinyIdInfo.getBizType());
if (row == 1) {
tinyIdInfo.setMaxId(newMaxId);
SegmentId segmentId = convert(tinyIdInfo);
logger.info("getNextSegmentId success tinyIdInfo:{} current:{}", tinyIdInfo, segmentId);
return segmentId;
} else {
logger.info("getNextSegmentId conflict tinyIdInfo:{}", tinyIdInfo);
}
}
throw new TinyIdSysException("get next segmentId conflict");
}
@SuppressWarnings("unchecked")
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(
propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public List<T> findListVOByParams(Map<String, Object> params) throws ServiceException, Exception {
List<T> returnList = null;
List<E> searchList = findListByParams(params, null);
if (searchList==null || searchList.size()<1) {
return returnList;
}
returnList=new ArrayList<T>();
for (E entity : searchList) {
Class<T> objectClass=GenericsUtils.getSuperClassGenricType(getClass(), 0);
T obj=objectClass.newInstance();
this.doMapper(entity, obj, this.getMapperIdPo2Vo());
returnList.add(obj);
}
return returnList;
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
@Override
public void onEvent(Event e) {
Order order = Order.fromJson(e.getContext());
while (true) {
DailyOrderReport report = repos.selectDailyOrderReportByKey(new java.sql.Date(order.getOrderTime().getTime()));
if (null == report) {
report = new DailyOrderReport();
report.setDay(new java.sql.Date(order.getOrderTime().getTime()));
report.setOrderNum(0L);
report.setOrderTotal(0L);
try {
repos.createDailyOrderReport(report);
} catch (DuplicateKeyException ex) {
log.warn("Duplicated message " + eventSerde.toJson(e));
}
} else {
report.setOrderNum(1L);
report.setOrderTotal(Long.valueOf(order.getOrderAmount()));
repos.updateDailyOrderReport(report);
break;
}
}
}
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(
propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
@SuppressWarnings("unchecked")
public DefaultResult<T> findByUK(T object) throws ServiceException, Exception {
if (object==null || !(object instanceof BaseValueObj) ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
Class<T> valueObjectClass=GenericsUtils.getSuperClassGenricType(getClass(), 0);
Class<E> entityObjectClass=GenericsUtils.getSuperClassGenricType(getClass(), 1);
E entityObject=entityObjectClass.newInstance();
T objectByUK=null;
try {
this.doMapper(object, entityObject, this.getMapperIdVo2Po());
E entityByUK=this.getBaseDataAccessObject().findByUK(entityObject);
if (entityByUK!=null) {
objectByUK=valueObjectClass.newInstance();
this.doMapper(entityByUK, objectByUK, this.getMapperIdPo2Vo());
}
} catch (Exception e) {
e.printStackTrace();
}
DefaultResult<T> result=new DefaultResult<T>();
if (objectByUK!=null && !StringUtils.isBlank( ((BaseValueObj)objectByUK).getOid() ) ) {
result.setValue(objectByUK);
} else {
result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
return result;
}
@SuppressWarnings("rawtypes")
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public int countByPK(E entityObject) throws ServiceException, Exception {
if (entityObject==null || !(entityObject instanceof BaseEntity) ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
Map<String, Object> pkMap=BaseEntityUtil.getPKParameter((BaseEntity)entityObject);
if (pkMap==null || pkMap.size()<1) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_INCORRECT));
}
return this.getBaseDataAccessObject().countByPK(pkMap);
}
@Transactional(isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public DefaultResult<List<E>> ibatisSelectListByParams(Map<String, Object> params) throws ServiceException, Exception {
if (params == null) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
DefaultResult<List<E>> result=new DefaultResult<List<E>>();
List<E> searchList = (List<E>)this.getBaseDataAccessObject().ibatisSelectListByParams(params);
if (searchList!=null && searchList.size()>0) {
result.setValue(searchList);
} else {
result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
return result;
}
@Transactional(isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public DefaultResult<E> ibatisSelectOneByValue(E valueObj) throws ServiceException, Exception {
if (null==valueObj) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
DefaultResult<E> result = new DefaultResult<E>();
E searchResult = this.getBaseDataAccessObject().ibatisSelectOneByValue(valueObj);
if (searchResult!=null) {
result.setValue(searchResult);
} else {
result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
return result;
}
@Override
@Caching(evict = {
@CacheEvict(value = "projects",key = "1"),
@CacheEvict(value = "projectPageNum",key = "1")
})
@Transactional(isolation = Isolation.READ_COMMITTED)
public void addPro(Project project){
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
project.setDate(timestamp);
projectMapper.insert(project);
}
@SuppressWarnings("unchecked")
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(
propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public DefaultResult<T> findObjectByOid(T object) throws ServiceException, Exception {
if (object==null || !(object instanceof BaseValueObj) ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
Class<T> valueObjectClass=GenericsUtils.getSuperClassGenricType(getClass(), 0);
Class<E> entityObjectClass=GenericsUtils.getSuperClassGenricType(getClass(), 1);
E entityObject=entityObjectClass.newInstance();
T objectByOid=null;
try {
this.doMapper(object, entityObject, this.getMapperIdVo2Po());
E entityByOid=this.findByOid(entityObject);
if (entityByOid!=null) {
objectByOid=valueObjectClass.newInstance();
this.doMapper(entityByOid, objectByOid, this.getMapperIdPo2Vo());
}
} catch (Exception e) {
e.printStackTrace();
}
DefaultResult<T> result=new DefaultResult<T>();
if (objectByOid!=null && !StringUtils.isBlank( ((BaseValueObj)objectByOid).getOid() ) ) {
result.setValue(objectByOid);
} else {
result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
return result;
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public Info updateAvatar(HttpServletRequest request) {
String url = uploadPic(request).getUrl();
if (!"".equals(url)) {
infoSer.updateAvatar(url);
}
return infoSer.getInfo();
}
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public int countByPKng(PK pk) throws ServiceException, Exception {
if (pk==null) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
return this.getBaseDataAccessObject().countByPK((String)pk);
}
@Transactional(isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public DefaultResult<E> ibatisSelectOneByValue(E valueObj) throws ServiceException, Exception {
if (null==valueObj) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
DefaultResult<E> result = new DefaultResult<E>();
E searchResult = this.getBaseDataAccessObject().ibatisSelectOneByValue(valueObj);
if (searchResult!=null) {
result.setValue(searchResult);
} else {
result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
return result;
}
@Override
@Transactional(isolation = Isolation.READ_COMMITTED)
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public Action cancelAction(final long actionId) {
LOG.debug("cancelAction({})", actionId);
final JpaAction action = actionRepository.findById(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (action.isCancelingOrCanceled()) {
throw new CancelActionNotAllowedException("Actions in canceling or canceled state cannot be canceled");
}
if (action.isActive()) {
LOG.debug("action ({}) was still active. Change to {}.", action, Status.CANCELING);
action.setStatus(Status.CANCELING);
// document that the status has been retrieved
actionStatusRepository.save(new JpaActionStatus(action, Status.CANCELING, System.currentTimeMillis(),
RepositoryConstants.SERVER_MESSAGE_PREFIX + "manual cancelation requested"));
final Action saveAction = actionRepository.save(action);
onlineDsAssignmentStrategy.cancelAssignment(action);
return saveAction;
} else {
throw new CancelActionNotAllowedException(action.getId() + " is not active and cannot be canceled");
}
}
@Override
@Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
public List<ProviderUserModel> getUsersByProviderConfigId(Long providerConfigId) {
if (null == providerConfigId) {
return List.of();
}
return providerUserRepository.findByProviderConfigId(providerConfigId)
.stream()
.map(this::convertToUserModel)
.collect(Collectors.toList());
}
@Transactional(isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public DefaultResult<List<E>> ibatisSelectListByParams(Map<String, Object> params) throws ServiceException, Exception {
if (params == null) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
DefaultResult<List<E>> result=new DefaultResult<List<E>>();
List<E> searchList = (List<E>)this.getBaseDataAccessObject().ibatisSelectListByParams(params);
if (searchList!=null && searchList.size()>0) {
result.setValue(searchList);
} else {
result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
return result;
}
@SuppressWarnings("unchecked")
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(
propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public DefaultResult<T> findObjectByOid(T object) throws ServiceException, Exception {
if (object==null || !(object instanceof BaseValueObj) ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.OBJ_NULL));
}
Class<T> valueObjectClass=GenericsUtils.getSuperClassGenricType(getClass(), 0);
Class<E> entityObjectClass=GenericsUtils.getSuperClassGenricType(getClass(), 1);
E entityObject=entityObjectClass.newInstance();
T objectByOid=null;
try {
this.doMapper(object, entityObject, this.getMapperIdVo2Po());
E entityByOid=this.findByOid(entityObject);
if (entityByOid!=null) {
objectByOid=valueObjectClass.newInstance();
this.doMapper(entityByOid, objectByOid, this.getMapperIdPo2Vo());
}
} catch (Exception e) {
e.printStackTrace();
}
DefaultResult<T> result=new DefaultResult<T>();
if (objectByOid!=null && !StringUtils.isBlank( ((BaseValueObj)objectByOid).getOid() ) ) {
result.setValue(objectByOid);
} else {
result.setSystemMessage(new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
return result;
}
@Override
@Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
public List<SystemMessageModel> getSystemMessagesAfter(OffsetDateTime date) {
OffsetDateTime currentTime = DateUtils.createCurrentDateTimestamp();
return convertAllToSystemMessageModel(systemMessageRepository.findByCreatedBetween(date, currentTime));
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
@Override
public void createDailyOrderReport(DailyOrderReport report) {
dailyDao.insert(report);
}