org.springframework.transaction.annotation.Transactional Java Examples

The following examples show how to use org.springframework.transaction.annotation.Transactional. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Spring-Security-Third-Edition   Author: PacktPublishing   File: UserDetailsServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    CalendarUser user = userRepository.findByEmail(username);

    if (user == null)
        throw new UsernameNotFoundException("username " + username
                + " not found");

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()){
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
 
Example #2
Source Project: projectforge-webapp   Author: micromata   File: Kost1Dao.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets kost1 as string. Extends access: Users have read access to the number of their own kost1.
 * @param id
 * @return
 */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public String getKostString(final Integer id)
{
  if (id == null) {
    return "";
  }
  final Kost1DO kost1 = internalGetById(id);
  if (kost1 == null) {
    return "";
  }
  if (hasLoggedInUserSelectAccess(kost1, false) == true) {
    return KostFormatter.format(kost1);
  } else {
    final EmployeeDO employee = userGroupCache.getEmployee(PFUserContext.getUserId());
    if (employee != null && employee.getKost1Id() != null && employee.getKost1Id().compareTo(id) == 0) {
      kost1.setDescription(""); // Paranoia (if KostFormatter shows description in future times and Kost1DO is not visible for the user).
      return KostFormatter.format(kost1);
    }
  }
  return null;
}
 
Example #3
Source Project: zstack   Author: zstackio   File: VmDeleteVolumeFlow.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional
private void detachDataVolumes(VmInstanceSpec spec) {
    List<String> dataVolumeUuids = CollectionUtils.transformToList(spec.getVmInventory().getAllVolumes(), new Function<String, VolumeInventory>() {
        @Override
        public String call(VolumeInventory arg) {
            return VolumeType.Data.toString().equals(arg.getType()) ? arg.getUuid() : null;
        }
    });

    if (dataVolumeUuids == null || dataVolumeUuids.isEmpty()) {
        return;
    }

    //NOTE(weiw): not using batch sql to avoid deadlock
    for (String volumeUuid: dataVolumeUuids) {
        String sql = "update VolumeVO vol set vol.vmInstanceUuid = null where vol.uuid in (:uuids)";
        Query q = dbf.getEntityManager().createQuery(sql);
        q.setParameter("uuids", volumeUuid);
        q.executeUpdate();
    }
}
 
Example #4
Source Project: syncope   Author: apache   File: JPAAnyObjectDAO.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
@Override
@SuppressWarnings("unchecked")
public List<Group> findDynGroups(final String key) {
    Query query = entityManager().createNativeQuery(
            "SELECT group_id FROM " + JPAGroupDAO.ADYNMEMB_TABLE + " WHERE any_id=?");
    query.setParameter(1, key);

    List<Group> result = new ArrayList<>();
    query.getResultList().stream().map(resultKey -> resultKey instanceof Object[]
            ? (String) ((Object[]) resultKey)[0]
            : ((String) resultKey)).
            forEach(groupKey -> {
                Group group = groupDAO.find(groupKey.toString());
                if (group == null) {
                    LOG.error("Could not find group {}, even though returned by the native query", groupKey);
                } else if (!result.contains(group)) {
                    result.add(group);
                }
            });
    return result;
}
 
Example #5
Source Project: webanno   Author: webanno   File: TelemetryServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public <T> Optional<TelemetrySettings> readSettings(TelemetrySupport<T> aSupport)
{
    String query = 
            "FROM TelemetrySettings " + 
            "WHERE support = :support";
    
    List<TelemetrySettings> results = entityManager.createQuery(query, TelemetrySettings.class)
        .setParameter("support", aSupport.getId())
        .getResultList();
    
    if (results.isEmpty()) {
        return Optional.empty();
    }
    
    return Optional.of(results.get(0));
}
 
Example #6
Source Project: paascloud-master   Author: paascloud   File: UacMenuServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(readOnly = true, rollbackFor = Exception.class)
public ViewMenuVo getViewVoById(Long id) {
	Preconditions.checkArgument(id != null, "菜单ID不能为空");
	UacMenu menu = uacMenuMapper.selectByPrimaryKey(id);

	if (menu == null) {
		logger.error("找不到菜单信息id={}", id);
		throw new UacBizException(ErrorCodeEnum.UAC10013003, id);
	}

	// 获取父级菜单信息
	UacMenu parentMenu = uacMenuMapper.selectByPrimaryKey(menu.getPid());

	ModelMapper modelMapper = new ModelMapper();
	ViewMenuVo menuVo = modelMapper.map(menu, ViewMenuVo.class);

	if (parentMenu != null) {
		menuVo.setParentMenuName(parentMenu.getMenuName());
	}

	return menuVo;
}
 
Example #7
Source Project: jeecg-boot-with-activiti   Author: smallyunet   File: JeecgDemoServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 事务控制在service层面
 * 加上注解:@Transactional,声明的方法就是一个独立的事务(有异常DB操作全部回滚)
 */
@Override
@Transactional
public void testTran() {
	JeecgDemo pp = new JeecgDemo();
	pp.setAge(1111);
	pp.setName("测试事务  小白兔 1");
	jeecgDemoMapper.insert(pp);
	
	JeecgDemo pp2 = new JeecgDemo();
	pp2.setAge(2222);
	pp2.setName("测试事务  小白兔 2");
	jeecgDemoMapper.insert(pp2);
	
	Integer.parseInt("hello");//自定义异常
	
	JeecgDemo pp3 = new JeecgDemo();
	pp3.setAge(3333);
	pp3.setName("测试事务  小白兔 3");
	jeecgDemoMapper.insert(pp3);
	return ;
}
 
Example #8
Source Project: molgenis   Author: molgenis   File: RepositoryCopier.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Transactional
public Repository<Entity> copyRepository(
    Repository<Entity> repository, String entityTypeId, Package pack, String entityTypeLabel) {
  LOG.info(
      "Creating a copy of {} repository, with id: {}, package: {} and label: {}",
      repository.getName(),
      entityTypeId,
      pack,
      entityTypeLabel);

  // create copy of entity meta data
  EntityType emd =
      EntityType.newInstance(repository.getEntityType(), DEEP_COPY_ATTRS, attrFactory);
  emd.setId(entityTypeId);
  emd.setLabel(entityTypeLabel);
  emd.setPackage(pack);
  // create repository for copied entity meta data
  Repository<Entity> repositoryCopy = metaDataService.createRepository(emd);

  // copy data to new repository
  repositoryCopy.add(repository.query().findAll());
  return repositoryCopy;
}
 
Example #9
Source Project: TeamDojo   Author: otto-de   File: BadgeResourceIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
public void updateNonExistingBadge() throws Exception {
    int databaseSizeBeforeUpdate = badgeRepository.findAll().size();

    // Create the Badge
    BadgeDTO badgeDTO = badgeMapper.toDto(badge);

    // If the entity doesn't have an ID, it will be created instead of just being updated
    restBadgeMockMvc.perform(put("/api/badges")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(badgeDTO)))
        .andExpect(status().isCreated());

    // Validate the Badge in the database
    List<Badge> badgeList = badgeRepository.findAll();
    assertThat(badgeList).hasSize(databaseSizeBeforeUpdate + 1);
}
 
Example #10
Source Project: bamboobsc   Author: billchen198318   File: SystemBeanHelpLogicServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source Project: alchemy   Author: binglind   File: SinkResourceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
public void createSinkWithExistingId() throws Exception {
    int databaseSizeBeforeCreate = sinkRepository.findAll().size();

    // Create the Sink with an existing ID
    sink.setId(1L);
    SinkDTO sinkDTO = sinkMapper.toDto(sink);

    // An entity with an existing ID cannot be created, so this API call must fail
    restSinkMockMvc.perform(post("/api/sinks")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(sinkDTO)))
        .andExpect(status().isBadRequest());

    // Validate the Sink in the database
    List<Sink> sinkList = sinkRepository.findAll();
    assertThat(sinkList).hasSize(databaseSizeBeforeCreate);
}
 
Example #12
Source Project: bbs   Author: diyhi   File: FollowServiceBean.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 根据用户名称查询粉丝数量
 * @param userId 用户Id
 * @param userName 用户名称
 * @return
 */
@Transactional(readOnly=true, propagation=Propagation.NOT_SUPPORTED)
public Long findFollowerCountByUserName(Long userId,String userName){
	Long count = 0L;
	//表编号
	int tableNumber = followerConfig.userIdRemainder(userId);
	Query query  = null;
	
	if(tableNumber == 0){//默认对象
		query = em.createQuery("select count(o) from Follower o where o.userName=?1");
		query.setParameter(1, userName);
		count = (Long)query.getSingleResult();
		
	}else{//带下划线对象
		query = em.createQuery("select count(o) from Follower_"+tableNumber+" o where o.userName=?1");
		query.setParameter(1, userName);
		count = (Long)query.getSingleResult();
	}
	return count;
}
 
Example #13
Source Project: smart-admin   Author: 1024-lab   File: DepartmentService.java    License: MIT License 5 votes vote down vote up
/**
 * 新增添加部门
 *
 * @param departmentCreateDTO
 * @return AjaxResult
 */
@Transactional(rollbackFor = Exception.class)
public ResponseDTO<String> addDepartment(DepartmentCreateDTO departmentCreateDTO) {
    DepartmentEntity departmentEntity = SmartBeanUtil.copy(departmentCreateDTO, DepartmentEntity.class);
    departmentEntity.setSort(0L);
    departmentDao.insert(departmentEntity);
    departmentEntity.setSort(departmentEntity.getId());
    departmentDao.updateById(departmentEntity);
    return ResponseDTO.succ();
}
 
Example #14
Source Project: tutorials   Author: eugenp   File: CarResourceIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
@Transactional
public void getCar() throws Exception {
    // Initialize the database
    carRepository.saveAndFlush(car);

    // Get the car
    restCarMockMvc.perform(get("/api/cars/{id}", car.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.id").value(car.getId().intValue()))
        .andExpect(jsonPath("$.make").value(DEFAULT_MAKE.toString()))
        .andExpect(jsonPath("$.brand").value(DEFAULT_BRAND.toString()))
        .andExpect(jsonPath("$.price").value(DEFAULT_PRICE.doubleValue()));
}
 
Example #15
Source Project: OneBlog   Author: zhangyd-c   File: SysUpdateRecordeServiceImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public UpdateRecorde insert(UpdateRecorde entity){
    Assert.notNull(entity, "UpdateRecorde不可为空!");
    entity.setUpdateTime(new Date());
    entity.setCreateTime(new Date());
    sysUpdateRecordeMapper.insertSelective(entity.getSysUpdateRecorde());
    return entity;
}
 
Example #16
Source Project: alchemy   Author: binglind   File: JobSqlServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get one jobSql by id.
 *
 * @param id the id of the entity.
 * @return the entity.
 */
@Override
@Transactional(readOnly = true)
public Optional<JobSqlDTO> findOne(Long id) {
    log.debug("Request to get JobSql : {}", id);
    return jobSqlRepository.findById(id)
        .map(jobSqlMapper::toDto);
}
 
Example #17
Source Project: bbs   Author: diyhi   File: UserRoleServiceBean.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 根据Id查询角色
 * @param userRoleId 角色Id
 * @return
 */
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public UserRole findRoleById(String userRoleId){
	Query query =  em.createQuery("select o from UserRole o where o.id=?1");
	query.setParameter(1, userRoleId);
	List<UserRole> userRoleList = query.getResultList();
	if(userRoleList != null && userRoleList.size() >0){
		for(UserRole userRole : userRoleList){
			return userRole;
		}
	}
	return null;
}
 
Example #18
Source Project: TeamDojo   Author: otto-de   File: CommentResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void getAllCommentsByCreationDateIsNullOrNotNull() throws Exception {
    // Initialize the database
    commentRepository.saveAndFlush(comment);

    // Get all the commentList where creationDate is not null
    defaultCommentShouldBeFound("creationDate.specified=true");

    // Get all the commentList where creationDate is null
    defaultCommentShouldNotBeFound("creationDate.specified=false");
}
 
Example #19
Source Project: Full-Stack-Development-with-JHipster   Author: PacktPublishing   File: AccountResourceIntTest.java    License: MIT License 5 votes vote down vote up
@Test
@Transactional
@WithMockUser("save-existing-email")
public void testSaveExistingEmail() throws Exception {
    User user = new User();
    user.setLogin("save-existing-email");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);

    userRepository.saveAndFlush(user);

    User anotherUser = new User();
    anotherUser.setLogin("save-existing-email2");
    anotherUser.setEmail("[email protected]");
    anotherUser.setPassword(RandomStringUtils.random(60));
    anotherUser.setActivated(true);

    userRepository.saveAndFlush(anotherUser);

    UserDTO userDTO = new UserDTO();
    userDTO.setLogin("not-used");
    userDTO.setFirstName("firstname");
    userDTO.setLastName("lastname");
    userDTO.setEmail("[email protected]");
    userDTO.setActivated(false);
    userDTO.setImageUrl("http://placehold.it/50x50");
    userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
    userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));

    restMvc.perform(
        post("/api/account")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(userDTO)))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
    assertThat(updatedUser.getEmail()).isEqualTo("[email protected]");
}
 
Example #20
Source Project: Spring-5.0-Projects   Author: PacktPublishing   File: UserServiceIntTest.java    License: MIT License 5 votes vote down vote up
@Test
@Transactional
public void testRemoveNotActivatedUsers() {
    // custom "now" for audit to use as creation date
    when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS)));

    user.setActivated(false);
    userRepository.saveAndFlush(user);

    assertThat(userRepository.findOneByLogin("johndoe")).isPresent();
    userService.removeNotActivatedUsers();
    assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent();
}
 
Example #21
Source Project: paascloud-master   Author: paascloud   File: UacMenuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(readOnly = true, rollbackFor = Exception.class)
public List<UacMenu> getAllChildMenuByMenuId(Long menuId, String menuStatus) {
	UacMenu uacMenuQuery = new UacMenu();
	uacMenuQuery.setId(menuId);
	uacMenuQuery = mapper.selectOne(uacMenuQuery);
	List<UacMenu> uacMenuList = Lists.newArrayList();
	uacMenuList = buildNode(uacMenuList, uacMenuQuery, menuStatus);
	return uacMenuList;
}
 
Example #22
Source Project: syncope   Author: apache   File: JPAAnyUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional
@Override
public void addAttr(final String key, final PlainSchema schema, final String value) {
    Any any = dao().find(key);

    Set<AnyTypeClass> typeOwnClasses = new HashSet<>();
    typeOwnClasses.addAll(any.getType().getClasses());
    typeOwnClasses.addAll(any.getAuxClasses());
    if (!typeOwnClasses.stream().anyMatch(clazz -> clazz.getPlainSchemas().contains(schema))) {
        LOG.warn("Schema {} not allowed for {}, ignoring", schema, any);
        return;
    }

    PlainAttr<?> attr = (PlainAttr<?>) any.getPlainAttr(schema.getKey()).orElse(null);
    if (attr == null) {
        attr = newPlainAttr();
        attr.setSchema(schema);
        ((PlainAttr) attr).setOwner(any);
        any.add(attr);

        try {
            attr.add(value, this);
            dao().save(any);
        } catch (InvalidPlainAttrValueException e) {
            LOG.error("Invalid value for attribute {} and {}: {}", schema.getKey(), any, value, e);
        }
    } else {
        LOG.debug("{} has already {} set: {}", any, schema.getKey(), attr.getValuesAsStrings());
    }
}
 
Example #23
Source Project: pazuzu-registry   Author: pazuzu-io   File: FeatureService.java    License: MIT License 5 votes vote down vote up
/**
 * Search feature base on give search criteria, ordered by name.
 * @param name string the name should contains.
 * @param author string the author should contains.
 * @param status the status of the feature, if not present do no filter on status.
 * @param offset the offset of the result list (must be present)
 * @param limit the maximum size of the returned list (must be present)
 * @param converter the converter that will be used to map the feature to the expected result type
 * @param <T> the list item result type
 * @return paginated list of feature that match the search criteria with the totcal count.
 * @throws ServiceException
 */
@Transactional
public <T> FeaturesPage<Feature, T> searchFeatures(String name, String author, FeatureStatus status,
                                          Integer offset, Integer limit,
                                          Function<Feature, T> converter) throws ServiceException {
    Specification<Feature> spec = (root, query, builder) -> {
        List<Predicate> predicates = new ArrayList<>();

        if (name != null) {
            predicates.add(builder.like(builder.lower(root.get(Feature_.name)), escapeLike(name), '|' ));
        }

        if (author != null) {
            predicates.add(builder.like(builder.lower(root.get(Feature_.author)), escapeLike(author), '|'));
        }

        if (status != null) {
            predicates.add(builder.equal(root.get(Feature_.status), status));
        }

        return builder.and(predicates.toArray(new Predicate[predicates.size()]));
    };
    Pageable pageable = new PageRequest(offset / limit, limit, Sort.Direction.ASC, "name");
    Page<Feature> page = featureRepository.findAll(spec, pageable);
    return new FeaturesPage<>(page, converter);

}
 
Example #24
Source Project: jshERP   Author: jishenghua   File: UserBusinessService.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
public int insertUserBusiness(String beanJson, HttpServletRequest request) throws Exception {
    UserBusiness userBusiness = JSONObject.parseObject(beanJson, UserBusiness.class);
    int result=0;
    try{
        result=userBusinessMapper.insertSelective(userBusiness);
        logService.insertLog("关联关系", BusinessConstants.LOG_OPERATION_TYPE_ADD, request);
    }catch(Exception e){
        JshException.writeFail(logger, e);
    }
    return result;
}
 
Example #25
Source Project: spring4-sandbox   Author: hantsy   File: AnnotationConfigJpaConferenceDaoImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
@Transactional
public void beforeTestCase() {
	log.debug("===================before test=====================");

	conferenceDao.deleteAll();
}
 
Example #26
Source Project: SeaCloudsPlatform   Author: SeaCloudsEU   File: TemplateDAOJpa.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public ITemplate save(ITemplate template) {
    logger.info("template.getUuid() "+template.getUuid());
    entityManager.persist(template);
    entityManager.flush();
    return template;
}
 
Example #27
Source Project: TeamDojo   Author: otto-de   File: CommentResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void getAllCommentsByCreationDateIsEqualToSomething() throws Exception {
    // Initialize the database
    commentRepository.saveAndFlush(comment);

    // Get all the commentList where creationDate equals to DEFAULT_CREATION_DATE
    defaultCommentShouldBeFound("creationDate.equals=" + DEFAULT_CREATION_DATE);

    // Get all the commentList where creationDate equals to UPDATED_CREATION_DATE
    defaultCommentShouldNotBeFound("creationDate.equals=" + UPDATED_CREATION_DATE);
}
 
Example #28
Source Project: bamboobsc   Author: billchen198318   File: ReportRoleViewLogicServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@ServiceMethodAuthority(type={ServiceMethodType.INSERT, ServiceMethodType.UPDATE})
@Transactional(
		propagation=Propagation.REQUIRED, 
		readOnly=false,
		rollbackFor={RuntimeException.class, IOException.class, Exception.class} )			
@Override
public DefaultResult<Boolean> create(String roleOid, List<String> emplOids, List<String> orgaOids) throws ServiceException, Exception {
	if ( super.isNoSelectId(roleOid) ) {
		throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
	}
	RoleVO role = new RoleVO();
	role.setOid(roleOid);
	DefaultResult<RoleVO> rResult = this.getRoleService().findObjectByOid(role);
	if ( rResult.getValue() == null ) {
		throw new ServiceException( rResult.getSystemMessage().getValue() );
	}
	role = rResult.getValue();
	this.deleteByRole( role.getRole() );		
	for (int i=0; emplOids!=null && i<emplOids.size(); i++) {
		EmployeeVO employee = this.findEmployeeData( emplOids.get(i) );		
		this.createReportRoleView(role.getRole(), ReportRoleViewTypes.IS_EMPLOYEE, employee.getAccount());			
	}
	for (int i=0; orgaOids!=null && i<orgaOids.size(); i++) {
		OrganizationVO organization = this.findOrganizationData( orgaOids.get(i) );
		this.createReportRoleView(role.getRole(), ReportRoleViewTypes.IS_ORGANIZATION, organization.getOrgId());
	}		
	DefaultResult<Boolean> result = new DefaultResult<Boolean>();
	result.setValue(Boolean.TRUE);
	result.setSystemMessage( new SystemMessage( SysMessageUtil.get(GreenStepSysMsgConstants.UPDATE_SUCCESS) ) );
	return result;
}
 
Example #29
Source Project: wallride   Author: tagbangers   File: TagService.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@CacheEvict(value = {WallRideCacheConfiguration.ARTICLE_CACHE, WallRideCacheConfiguration.PAGE_CACHE}, allEntries = true)
public List<Tag> bulkDeleteTag(TagBulkDeleteRequest bulkDeleteRequest, final BindingResult result) {
	List<Tag> tags = new ArrayList<>();
	for (long id : bulkDeleteRequest.getIds()) {
		final TagDeleteRequest deleteRequest = new TagDeleteRequest.Builder()
				.id(id)
				.language(bulkDeleteRequest.getLanguage())
				.build();

		final BeanPropertyBindingResult r = new BeanPropertyBindingResult(deleteRequest, "request");
		r.setMessageCodesResolver(messageCodesResolver);

		TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
		transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
		Tag tag = null;
		try {
			tag = transactionTemplate.execute(new TransactionCallback<Tag>() {
				public Tag doInTransaction(TransactionStatus status) {
					return deleteTag(deleteRequest, result);
				}
			});
			tags.add(tag);
		} catch (Exception e) {
			logger.debug("Errors: {}", r);
			result.addAllErrors(r);
		}
	}
	return tags;
}
 
Example #30
Source Project: Moss   Author: SpringCloud   File: DictServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public void updateDictType(DictTypeModel dictTypeModel) {

    DictType dictType=dictTypeMapper.selectById(dictTypeModel.getId());
    if(null==dictType){
        return ;
    }
    dictType.setGmtModified(new Timestamp(System.currentTimeMillis()));
    dictTypeMapper.updateById(BeanMapper.map(dictTypeModel,DictType.class));

}