下面列出了怎么用org.springframework.transaction.annotation.Propagation的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 根据话题Id查询被点赞数量
* @param topicId 话题Id
* @return
*/
@Transactional(readOnly=true, propagation=Propagation.NOT_SUPPORTED)
public Long findLikeCountByTopicId(Long topicId){
Long count = 0L;
//表编号
int tableNumber = topicLikeConfig.topicIdRemainder(topicId);
Query query = null;
if(tableNumber == 0){//默认对象
query = em.createQuery("select count(o) from TopicLike o where o.topicId=?1");
query.setParameter(1, topicId);
count = (Long)query.getSingleResult();
}else{//带下划线对象
query = em.createQuery("select count(o) from TopicLike_"+tableNumber+" o where o.topicId=?1");
query.setParameter(1, topicId);
count = (Long)query.getSingleResult();
}
return count;
}
@PutMapping(value = "/models/{modelId}", name = "模型修改")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public ModelResponse updateModel(@PathVariable String modelId, @RequestBody ModelRequest modelRequest) {
Model model = getModelFromRequest(modelId);
model.setCategory(modelRequest.getCategory());
if (!modelRequest.getKey().equals(model.getKey())) {
checkModelKeyExists(modelRequest.getKey());
managementService.executeCommand(new UpdateModelKeyCmd(modelId, modelRequest.getKey()));
}
model.setKey(modelRequest.getKey());
model.setName(modelRequest.getName());
model.setMetaInfo(modelRequest.getMetaInfo());
model.setTenantId(modelRequest.getTenantId());
repositoryService.saveModel(model);
return restResponseFactory.createModelResponse(model);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
Exception.class)
public boolean[] updateUrl(int id, String oldLocalUrl, String localUrl, String visitUrl) {
boolean[] b = new boolean[]{false, false};
boolean canUpdateLocalUrl = Checker.isExists(oldLocalUrl) && Checker.isNotEmpty(localUrl) && Checker
.isNotExists(localUrl) && !localUrlExists(localUrl);
if (canUpdateLocalUrl) {
FileExecutor.renameTo(oldLocalUrl, localUrl);
fileDAO.updateLocalUrlById(id, localUrl);
b[0] = true;
}
if (Checker.isNotEmpty(visitUrl) && !visitUrlExists(visitUrl)) {
fileDAO.updateVisitUrlById(id, visitUrl);
b[1] = true;
}
return b;
}
@ServiceMethodAuthority(type={ServiceMethodType.UPDATE})
@Transactional(
propagation=Propagation.REQUIRED,
readOnly=false,
rollbackFor={RuntimeException.class, IOException.class, Exception.class} )
@Override
public DefaultResult<OrganizationVO> update(OrganizationVO organization) throws ServiceException, Exception {
if (organization==null || super.isBlank(organization.getOid())) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
this.checkOrganizationIdIsZero(organization);
OrganizationVO dbOrganization = this.findOrganizationData(organization.getOid());
organization.setOrgId( dbOrganization.getOrgId() );
this.setStringValueMaxLength(organization, "description", MAX_DESCRIPTION_LENGTH);
this.handlerLongitudeAndLatitude(organization);
return this.getOrganizationService().updateObject(organization);
}
@ServiceMethodAuthority(type={ServiceMethodType.DELETE})
@Transactional(
propagation=Propagation.REQUIRED,
readOnly=false,
rollbackFor={RuntimeException.class, IOException.class, Exception.class} )
@Override
public DefaultResult<Boolean> deleteTemplate(SysFormTemplateVO template) throws ServiceException, Exception {
if ( null == template || super.isBlank(template.getOid()) ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
DefaultResult<SysFormTemplateVO> oldResult = this.sysFormTemplateService.findObjectByOid(template);
if ( oldResult.getValue() == null ) {
throw new ServiceException( oldResult.getSystemMessage().getValue() );
}
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("templateId", oldResult.getValue().getTplId());
if ( this.sysFormService.countByParams(paramMap) > 0 ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_CANNOT_DELETE));
}
return this.sysFormTemplateService.deleteObject(template);
}
/**
* 根据模板目录名称和布局类型和引用代码查询布局
* @param dirName 模板目录
* @param type 布局类型
* @param referenceCode 模块引用代码
* @return
*/
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public Layout findLayoutByReferenceCode(String dirName,Integer type,String referenceCode){
Query query = em.createQuery("select o from Layout o where o.dirName=?1 and o.type=?2 and o.referenceCode=?3");
//给SQL语句设置参数
query.setParameter(1, dirName);
query.setParameter(2, type);
query.setParameter(3, referenceCode);
List<Layout> layoutList = query.getResultList();
if(layoutList != null && layoutList.size() >0){
for(Layout layout : layoutList){
return layout;
}
}
return null;
}
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
public ListDto<UserAppDto> findDesktopUserApp(String userId) {
ListDto<UserAppDto> response = new ListDto<>(UserConstant.ERROR);
try {
StringUtils.isValidString(userId, "账号不允许为空");
List<UserApplication> apps = userApplicationRepository
.findByDesktopIconTrueAndUser(new User(userId));
response.setData(userAppConvert.covertToDto(apps));
response.setResult(UserConstant.SUCCESS);
} catch (VerificationException e) {
response.setErrorMessage(e.getMessage());
}
return response;
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public TXContext addAction(String serialNumber,ActionExecutePayload bean)throws Throwable{
// 新增事务Begin状态
TransactionInfo transactionInfo = new TransactionInfo();
transactionInfo.setTxId(TransactionIdGenerator.next());
transactionInfo.setParentId(Constants.TX_ROOT_ID); // 事务入口
transactionInfo.setContext(JSON.toJSONString(bean)); // 当前调用上下文环境
transactionInfo.setBusinessId(serialNumber); // 业务流水号
transactionInfo.setBusinessType(bean.getBizType()); // 业务类型
transactionInfo.setModuleId(bean.getModuleId());
transactionInfo.setTxType(bean.getTxType().getCode()); // TC | TCC
transactionInfo.setTxStatus(TransactionStatusEnum.BEGIN.getCode()); //begin状态
transactionInfo.setRetriedCount(JSON.toJSONString( // 设置重试次数
new RetryCount(defaultMsgRetryTimes, defaultCancelRetryTimes, defaultConfirmRetryTimes)));
createTransactionInfo(transactionInfo);
// 设置事务上下文
TXContextSupport ctx= new TXContextSupport();
ctx.setParentId(transactionInfo.getParentId());
ctx.setTxId(transactionInfo.getTxId());
ctx.setTxType(transactionInfo.getTxType());
ctx.setBusinessType(transactionInfo.getBusinessType());
ctx.setSerialNumber(serialNumber);
return ctx;
}
private Result createErrorResultForProvider(Throwable throwable, String propagatedBy, boolean attachRequired) {
CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
RemoteCoordinator compensableCoordinator = (RemoteCoordinator) beanFactory.getCompensableNativeParticipant();
RpcResult result = new RpcResult();
CompensableServiceFilter.InvocationResult wrapped = new CompensableServiceFilter.InvocationResult();
wrapped.setError(throwable);
if (attachRequired) {
wrapped.setVariable(Propagation.class.getName(), propagatedBy);
wrapped.setVariable(RemoteCoordinator.class.getName(), compensableCoordinator.getIdentifier());
}
result.setException(null);
result.setValue(wrapped);
return result;
}
/**
* 删除资源
* 删除时,需要先删除权限以及子节点资源
*
* @param ids 要删的资源ID列表
*/
@Override
@Transactional(rollbackFor = Exception.class, timeout = 60, propagation = Propagation.REQUIRED)
public void deleteResource(Long[] ids) {
for (Long i : ids) {
//先删权限
List<Permission> permissions = this.permissionRepository.findByResourceId(i);
if (!permissions.isEmpty()) {
this.permissionRepository.deleteAll(permissions);
}
//删除子节点
List<Resources> resources = this.resourcesRepository.findByParentId(i);
if (!resources.isEmpty()) {
this.resourcesRepository.deleteAll(resources);
}
//删除自己
this.resourcesRepository.deleteById(i);
// 删除资源日志记录
String optUserName = (String) SecurityUtils.getSubject().getPrincipal();
this.shiroEventListener.deleteResourceEvent(optUserName, ids);
}
}
@Override
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public int registerUser(String username, String password, String repeat_password, String phonenumber) {
if (!password.equals(repeat_password)) {
return 1;
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setPhonenumber(phonenumber);
User user1 = userMapper.selectUser(user);
if (user1 != null){
return 2;
}
userMapper.insert(user);
return 0;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table test
*
* @mbggenerated
*/
@Transactional(propagation=Propagation.REQUIRED,isolation =Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
public int insertSelective(List<Test> list) throws Exception {
int insertCount = 0;
if (list == null || list.size() == 0) {
return insertCount;
}
for (Test obj : list) {
if (obj == null) {
continue;
}
try {
insertCount += this.testMapper.insertSelective(obj);
} catch (Exception e) {
throw e;
}
}
return insertCount;
}
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
@Override
public void joinServer(String accessToken, UUID profileUUID, String serverid) throws ForbiddenOperationException {
Session session = sessionFactory.getCurrentSession();
Account account = loginService.loginWithToken(accessToken).getAccount();
GameProfile profile = session.get(GameProfile.class, profileUUID.toString());
if (profile == null || !account.equals(profile.getOwner())) {
throw new ForbiddenOperationException(MSG_INVALID_PROFILE);
}
if (profile.isBanned()) {
throw new ForbiddenOperationException(MSG_PROFILE_BANNED);
}
serveridRepo.createServerId(serverid, profileUUID);
}
@Override
@Transactional(
propagation = Propagation.REQUIRED,
readOnly = false)
@CacheEvict(
value = "greetings",
key = "#id")
public void delete(Long id) {
logger.info("> delete id:{}", id);
counterService.increment("method.invoked.greetingServiceBean.delete");
greetingRepository.delete(id);
logger.info("< delete id:{}", id);
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public List<ITemplate> getAll() {
TypedQuery<ITemplate> query = entityManager.createNamedQuery(
Template.QUERY_FIND_ALL, ITemplate.class);
List<ITemplate> templates = new ArrayList<ITemplate>();
templates = (List<ITemplate>) query.getResultList();
if (templates != null) {
logger.debug("Number of templates:" + templates.size());
} else {
logger.debug("No Result found.");
}
return templates;
}
@ServiceMethodAuthority(type={ServiceMethodType.INSERT})
@Transactional(
propagation=Propagation.REQUIRED,
readOnly=false,
rollbackFor={RuntimeException.class, IOException.class, Exception.class} )
@Override
public DefaultResult<SysBeanHelpExprMapVO> createExprMap(
SysBeanHelpExprMapVO beanHelpExprMap, String helpExprOid) throws ServiceException, Exception {
if (beanHelpExprMap==null || super.isBlank(helpExprOid)) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
SysBeanHelpExprVO sysBeanHelpExpr = new SysBeanHelpExprVO();
sysBeanHelpExpr.setOid(helpExprOid);
DefaultResult<SysBeanHelpExprVO> mResult = this.sysBeanHelpExprService.findObjectByOid(sysBeanHelpExpr);
if (mResult.getValue()==null) {
throw new ServiceException(mResult.getSystemMessage().getValue());
}
sysBeanHelpExpr = mResult.getValue(); // 查看有沒有資料
beanHelpExprMap.setHelpExprOid( sysBeanHelpExpr.getOid() );
return this.sysBeanHelpExprMapService.saveObject(beanHelpExprMap);
}
/**
* @param posString Format ###.## (<order number>.<position number>).
*/
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public AuftragsPositionDO getAuftragsPosition(final String posString)
{
Integer auftragsNummer = null;
Short positionNummer = null;
if (posString == null) {
return null;
}
final int sep = posString.indexOf('.');
if (sep <= 0 || sep + 1 >= posString.length()) {
return null;
}
auftragsNummer = NumberHelper.parseInteger(posString.substring(0, posString.indexOf('.')));
positionNummer = NumberHelper.parseShort(posString.substring(posString.indexOf('.') + 1));
if (auftragsNummer == null || positionNummer == null) {
log.info("Cannot parse order number (format ###.## expected: " + posString);
return null;
}
@SuppressWarnings("unchecked")
final List<AuftragDO> list = getHibernateTemplate().find("from AuftragDO k where k.nummer=?", auftragsNummer);
if (CollectionUtils.isEmpty(list) == true) {
return null;
}
return list.get(0).getPosition(positionNummer);
}
@Transactional (readOnly=true, propagation=Propagation.REQUIRED)
public Product getProduct (String uuid, String collection_uuid, User u)
{
Product p = productDao.getProductByUuid(uuid);
if (collectionDao.contains(collection_uuid, p.getId()))
return p;
return null;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public WarningUser findUserId(String id) throws IOException, MyException {
//To change body of implemented methods use File | Settings | File Templates.
WarningUser wu=new WarningUser();
Session session = getSession();
wu= (WarningUser) session.get(WarningUser.class,id);
return wu;
}
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(
propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED, timeout=25, readOnly=true)
public List<E> findListByParams(Map<String, Object> params) throws ServiceException, Exception {
return findListByParams(params, null);
}
@Override
@Scheduled(cron = "0 0 0 0/1 * ?")
@Transactional(propagation = Propagation.REQUIRED)
public void updateGroupByDay() throws IOException, MyException, JSchException {
logger.info("group day data upate begin...");
List<GroupDay> groups = getGroupInfoByDay();
Session session = getSession();
for (GroupDay group : groups) {
session.save(group);
}
logger.info("group day data upated end");
}
@Test
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void testGetEnforcementJobByAgreementId() throws Exception {
Provider provider = new Provider(null, UUID.randomUUID().toString(),
"Provider 2");
Template template = new Template();
template.setServiceId("service");
template.setText("asadsad");
template.setUuid(UUID.randomUUID().toString());
template.setProvider(provider);
providerDao.save(provider);
templateDao.save(template);
IAgreement agreement = newAgreement(provider, template);
agreementDao.save(agreement);
IEnforcementJob expected = newEnforcementJob(agreement);
enforcementJobDao.save(expected);
IEnforcementJob actual;
actual = service.getEnforcementJobByAgreementId(agreement.getAgreementId());
assertTrue(equalJobs(expected, actual));
actual = service.getEnforcementJobByAgreementId("noexiste");
assertNull(actual);
}
@Transactional(propagation = Propagation.REQUIRED)
public Rating updateRating(Rating rating, Long ratingId) {
Preconditions.checkNotNull(rating);
Preconditions.checkState(rating.getId() == ratingId);
Preconditions.checkNotNull(ratingRepository.findOne(ratingId));
return ratingRepository.save(rating);
}
@Transactional(
propagation=Propagation.REQUIRED,
readOnly=false,
rollbackFor={RuntimeException.class, IOException.class, Exception.class} )
@Override
public int deleteForEmpId(String empId) throws ServiceException, Exception {
if (StringUtils.isBlank(empId)) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
return this.monitorItemScoreDAO.deleteForEmpId(empId);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public WallpaperDto getUserTheme(String userId) {
WallpaperDto responseDto = new WallpaperDto(UserConstant.ERROR);
try {
if (!StringUtils.isLengthValid(userId,
UserConstant.USER_ID_MIN_LENGTH,
UserConstant.USER_ID_MAX_LENGTH)) {
log.info("[用户账号参数不合法]");
throw new VerificationException("用户账号参数不合法");
}
Wallpaper wallpaper = null;
Integer wallpaperId = userRepository.getUserTheme(userId);
if (wallpaperId == null || wallpaperId < 1) {
List<Wallpaper> ws = wallpaperRepository.findByIsDefaultTrue();
if (ws == null || ws.isEmpty()) {
log.fatal("错误,请管理员配置默认壁纸");
throw new VerificationException("系统错误");
}
wallpaper = ws.get(0);
} else {
wallpaper = wallpaperRepository.findOne(wallpaperId);
}
responseDto.setId(wallpaper.getId());
responseDto.setPath(wallpaper.getPath());
responseDto.setResult(UserConstant.SUCCESS);
} catch (VerificationException e) {
responseDto.setErrorMessage(e.getMessage());
}
return responseDto;
}
/**
* THIS METHOD IS NOT SAFE: IT MUST BE REMOVED.
* TODO: manage access by page.
* @param user_uuid
* @return
*/
@PreAuthorize ("hasRole('ROLE_DATA_MANAGER')")
@Transactional (readOnly=true, propagation=Propagation.REQUIRED)
public List<Long> getAuthorizedProducts (String user_uuid)
{
return productDao.getAuthorizedProducts (user_uuid);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testEntityManagerFactoryImplementsEntityManagerFactoryInfo() {
assertTrue(Proxy.isProxyClass(entityManagerFactory.getClass()));
assertTrue("Must have introduced config interface", entityManagerFactory instanceof EntityManagerFactoryInfo);
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory;
// assertEquals("Person", emfi.getPersistenceUnitName());
assertNotNull("PersistenceUnitInfo must be available", emfi.getPersistenceUnitInfo());
assertNotNull("Raw EntityManagerFactory must be available", emfi.getNativeEntityManagerFactory());
}
@Transactional(propagation = Propagation.SUPPORTS)
public boolean hasAccessToNetwork(UserVO user, NetworkVO network) {
if (!user.isAdmin()) {
long count = userDao.hasAccessToNetwork(user, network);
return count > 0;
}
return true;
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
void verifyApplicationContextSet() {
assertInTransaction(false);
assertNotNull(super.applicationContext,
"The application context should have been set due to ApplicationContextAware semantics.");
Employee employeeBean = (Employee) super.applicationContext.getBean("employee");
assertEquals(employeeBean.getName(), "John Smith", "employee's name.");
}
/**
* 根据资源表Id查询权限
* @param resourcesId 资源表Id
* @return
*/
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public List<SysPermission> findPermissionByResourcesId(String resourcesId){
Query query = em.createQuery("select b from SysPermissionResources a," +
"SysPermission b where a.permissionId = b.id and " +
"a.resourceId = ?1");
query.setParameter(1, resourcesId);
return query.getResultList();
}