Java Code Examples for org.springframework.transaction.annotation.Transactional

The following examples show how to use org.springframework.transaction.annotation.Transactional. These examples are extracted from open source projects.
Example 1
Project: Spring-Security-Third-Edition   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
Project: projectforge-webapp   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
Project: zstack   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
Project: syncope   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
Project: 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
Project: paascloud-master   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
Project: jeecg-boot-with-activiti   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
Project: 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
Project: TeamDojo   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
Project: bamboobsc   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
Project: alchemy   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
Project: bbs   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
Project: smart-admin   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
Project: tutorials   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
Project: OneBlog   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
Project: alchemy   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
Project: bbs   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
Project: TeamDojo   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
Project: Full-Stack-Development-with-JHipster   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
Project: Spring-5.0-Projects   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
Project: paascloud-master   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
Project: syncope   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
Project: pazuzu-registry   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
Project: jshERP   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
Project: spring4-sandbox   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
Project: SeaCloudsPlatform   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
Project: TeamDojo   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
Project: bamboobsc   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
Project: wallride   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
Project: Moss   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));

}
 
Example 31
Project: e-commerce-microservice   File: InvoiceResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void updateInvoice() throws Exception {
    // Initialize the database
    invoiceService.save(invoice);

    int databaseSizeBeforeUpdate = invoiceRepository.findAll().size();

    // Update the invoice
    Invoice updatedInvoice = invoiceRepository.findById(invoice.getId()).get();
    // Disconnect from session so that the updates on updatedInvoice are not directly saved in db
    em.detach(updatedInvoice);
    updatedInvoice
        .code(UPDATED_CODE)
        .date(UPDATED_DATE)
        .details(UPDATED_DETAILS)
        .status(UPDATED_STATUS)
        .paymentMethod(UPDATED_PAYMENT_METHOD)
        .paymentDate(UPDATED_PAYMENT_DATE)
        .paymentAmount(UPDATED_PAYMENT_AMOUNT);

    restInvoiceMockMvc.perform(put("/api/invoices")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(updatedInvoice)))
        .andExpect(status().isOk());

    // Validate the Invoice in the database
    List<Invoice> invoiceList = invoiceRepository.findAll();
    assertThat(invoiceList).hasSize(databaseSizeBeforeUpdate);
    Invoice testInvoice = invoiceList.get(invoiceList.size() - 1);
    assertThat(testInvoice.getCode()).isEqualTo(UPDATED_CODE);
    assertThat(testInvoice.getDate()).isEqualTo(UPDATED_DATE);
    assertThat(testInvoice.getDetails()).isEqualTo(UPDATED_DETAILS);
    assertThat(testInvoice.getStatus()).isEqualTo(UPDATED_STATUS);
    assertThat(testInvoice.getPaymentMethod()).isEqualTo(UPDATED_PAYMENT_METHOD);
    assertThat(testInvoice.getPaymentDate()).isEqualTo(UPDATED_PAYMENT_DATE);
    assertThat(testInvoice.getPaymentAmount()).isEqualTo(UPDATED_PAYMENT_AMOUNT);
}
 
Example 32
Project: cacheonix-core   File: EntityManagerClinic.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public Collection<Owner> findOwners(String lastName) {
	Query query = this.em.createQuery("SELECT owner FROM Owner owner WHERE owner.lastName LIKE :lastName");
	query.setParameter("lastName", lastName + "%");
	return query.getResultList();
}
 
Example 33
@Override
@Transactional( readOnly = true )
@SuppressWarnings( "unchecked" )
public <T extends DimensionalObject> List<T> getDataDimensionsNoAcl( Class<T> clazz )
{
    GenericDimensionalObjectStore<DimensionalObject> store = getDimensionalObjectStore( clazz );

    if ( store == null )
    {
        return new ArrayList<>();
    }

    return (List<T>) store.getByDataDimensionNoAcl( true );
}
 
Example 34
Project: mojito   File: BranchService.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional
public void deleteBranch(Long repositoryId, Long branchId) {
    deleteBranchAsset(branchId, repositoryId);

    Branch branch = branchRepository.findOne(branchId);
    logger.debug("Mark branch {} as deleted", branch.getName());
    branch.setDeleted(true);
    branchRepository.save(branch);
}
 
Example 35
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public CalendarUser findUserByEmail(String email) {
    if (email == null) {
        throw new IllegalArgumentException("email cannot be null");
    }
    try {
        return jdbcOperations.queryForObject(CALENDAR_USER_QUERY + "email = ?", CALENDAR_USER_MAPPER, email);
    } catch (EmptyResultDataAccessException notFound) {
        return null;
    }
}
 
Example 36
Project: Oauth2-Stateless-Authentication-with-Spring-and-JWT-Token   File: AccountService.java    License: MIT License 5 votes vote down vote up
@Transactional // To successfully remove the date @Transactional annotation must be added
public void removeAuthenticatedAccount() throws UsernameNotFoundException {
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    Account acct = findAccountByUsername(username);
    accountRepo.deleteAccountById(acct.getId());

}
 
Example 37
Project: cubeai   File: VerifyCodeResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void getVerifyCode() throws Exception {
    // Initialize the database
    verifyCodeRepository.saveAndFlush(verifyCode);

    // Get the verifyCode
    restVerifyCodeMockMvc.perform(get("/api/verify-codes/{id}", verifyCode.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.id").value(verifyCode.getId().intValue()))
        .andExpect(jsonPath("$.code").value(DEFAULT_CODE.toString()))
        .andExpect(jsonPath("$.expire").value(DEFAULT_EXPIRE.toString()));
}
 
Example 38
Project: ExamStack   File: ExamServiceImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Transactional
@Override
public void addExamUser(int examId,String userNameStr,HashMap<String,Role> roleMap){
	
	try {
		String[] userNames = userNameStr.split(";");
		List<User> userList = userMapper.getUserByNames(userNames, roleMap.get("ROLE_STUDENT").getRoleId());
		Exam exam = examMapper.getExamById(examId);
		ExamPaper examPaper = examPaperMapper.getExamPaperById(exam.getExamPaperId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
		Date now = new Date();
		for(User user : userList){
			ExamHistory history = this.getUserExamHistByUserIdAndExamId(user.getUserId(), examId, 0,1,2,3);
			if(history == null){
				history = new ExamHistory();
				history.setExamId(exam.getExamId());
				history.setExamPaperId(exam.getExamPaperId());
				history.setContent(examPaper.getContent());
				history.setDuration(examPaper.getDuration());
				//默认创建的记录都是审核通过的
				history.setApproved(1);
				String seriNo = sdf.format(now) + StringUtil.format(user.getUserId(), 3) + StringUtil.format(exam.getExamId(), 3);
				history.setSeriNo(seriNo);
				history.setVerifyTime(new Date());
				history.setUserId(user.getUserId());
				examMapper.addUserExamHist(history);
			}else if(history.getApproved() == 0){
				//审核状态是0的才允许重新添加
				examMapper.deleteUserExamHistByUserId(exam.getExamId(),user.getUserId());
				//批量添加的都是审核通过的记录
				history.setApproved(1);
				examMapper.addUserExamHist(history);
			}
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		throw new RuntimeException(e);
	}
}
 
Example 39
Project: bumblebee   File: BumblebeeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public String delGroup(Integer groupId) {
    if(null==groupId){
        return "fail";
    }
    //删除组
    bumblebeeDao.delGroup(groupId);
    //设置用户组为null
    bumblebeeDao.updateUserGroup(groupId);
    //删除组绑定的权限
    bumblebeeDao.delPermission(groupId);
    return "fail";
}
 
Example 40
Project: tutorials   File: QuoteResourceIntTest.java    License: MIT License 5 votes vote down vote up
@Test
@Transactional
public void getAllQuotesByPriceIsEqualToSomething() throws Exception {
    // Initialize the database
    quoteRepository.saveAndFlush(quote);

    // Get all the quoteList where price equals to DEFAULT_PRICE
    defaultQuoteShouldBeFound("price.equals=" + DEFAULT_PRICE);

    // Get all the quoteList where price equals to UPDATED_PRICE
    defaultQuoteShouldNotBeFound("price.equals=" + UPDATED_PRICE);
}