当前位置: 首页>>代码示例>>Java>>正文


Java Transactional类代码示例

本文整理汇总了Java中javax.transaction.Transactional的典型用法代码示例。如果您正苦于以下问题:Java Transactional类的具体用法?Java Transactional怎么用?Java Transactional使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Transactional类属于javax.transaction包,在下文中一共展示了Transactional类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: findAllFetchAuth

import javax.transaction.Transactional; //导入依赖的package包/类
/**
 * Retrieve all elements without pagination and includes authorizations..
 * 
 * @return all elements without pagination.
 */
@GET
@Path("withAuth")
@org.springframework.transaction.annotation.Transactional(readOnly = true)
public TableItem<SystemRoleVo> findAllFetchAuth() {
	final TableItem<SystemRoleVo> result = new TableItem<>();
	// get all roles
	final Map<Integer, SystemRoleVo> results = new TreeMap<>();
	fetchRoles(results);

	// fetch authorizations
	fetchAuthorizations(results);

	// apply pagination
	result.setData(new ArrayList<>(results.values()));
	result.setRecordsTotal(results.size());
	result.setRecordsTotal(results.size());
	return result;
}
 
开发者ID:ligoj,项目名称:bootstrap,代码行数:24,代码来源:RoleResource.java

示例2: importImageKeywordsFromCSV

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional(rollbackOn = Exception.class)
public Set<PhotoLocationImage> importImageKeywordsFromCSV(MultipartFile file, Course course, boolean store) throws IOException, BuenOjoCSVParserException {
	
	PhotoLocationExtraPhotosKeywordCSVParser parser = new PhotoLocationExtraPhotosKeywordCSVParser(file);
	
	Map <String,List<String>> map = parser.parse();
	ArrayList<PhotoLocationImage> images = new ArrayList<>();
	for(String name : map.keySet()) {
		
		PhotoLocationImage img = this.image(name, map.get(name),course);
		images.add(img);
	}
	
	if (store) {
		
		List<PhotoLocationImage> imgs = photoLocationImageRepository.save(images);
		return new HashSet<PhotoLocationImage>(imgs);
	}
	return new HashSet<PhotoLocationImage>(images);
	
}
 
开发者ID:GastonMauroDiaz,项目名称:buenojo,代码行数:22,代码来源:PhotoLocationAnnotatedResourceFactory.java

示例3: testRegisterInvalidLogin

import javax.transaction.Transactional; //导入依赖的package包/类
@Test
@Transactional
public void testRegisterInvalidLogin() throws Exception {
    UserDTO u = new UserDTO(
        "funky-log!n",          // login <-- invalid
        "password",             // password
        "Funky",                // firstName
        "One",                  // lastName
        "[email protected]",    // e-mail
        true,                   // activated
        "en",                   // langKey
        new HashSet<>(Arrays.asList(AuthoritiesConstants.USER))
    );

    restUserMockMvc.perform(
        post("/api/register")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(u)))
        .andExpect(status().isBadRequest());

    Optional<User> user = userRepository.findOneByEmail("[email protected]");
    assertThat(user.isPresent()).isFalse();
}
 
开发者ID:GastonMauroDiaz,项目名称:buenojo,代码行数:24,代码来源:AccountResourceTest.java

示例4: saveOrUpdate

import javax.transaction.Transactional; //导入依赖的package包/类
@Override
@Transactional
public void saveOrUpdate(RouteLeg leg) {
    RouteLeg dbLeg = entityManager.find(leg.getClass(), leg.getId());
    if (dbLeg != null) {
        dbLeg = leg;
        entityManager.merge(dbLeg);
    } else {
        log.warn("Route with id {} not found in DB, inserting as new...", leg.getId());
        try {
            saveRouteLeg(leg);
        } catch (DatabaseException e) {
            log.error("Fatal: could not save route leg to db: {}", e.getMessage());
        }
    }
}
 
开发者ID:RWTH-i5-IDSG,项目名称:xsharing-services-router,代码行数:17,代码来源:RouteLegRepositoryImpl.java

示例5: upsertPolicySetInTransaction

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional
private void upsertPolicySetInTransaction(final String policySetName, final ZoneEntity zone,
        final String policySetPayload) {
    PolicySetEntity existingPolicySetEntity = this.policySetRepository.getByZoneAndPolicySetId(zone, policySetName);
    PolicySetEntity policySetEntity = new PolicySetEntity(zone, policySetName, policySetPayload);

    // If policy Set already exists, set PK of entity for update
    if (null != existingPolicySetEntity) {
        LOGGER.debug("Found an existing policy set policySetName = {}, zone = {}, upserting now .", policySetName,
                zone);
        policySetEntity.setId(existingPolicySetEntity.getId());
    } else {
        LOGGER.debug("No existing policy set found for policySetName = {},  zone = {}, inserting now .",
                policySetName, zone);
    }

    this.cache.resetForPolicySet(zone.getName(), policySetName);
    this.policySetRepository.save(policySetEntity);
}
 
开发者ID:eclipse,项目名称:keti,代码行数:20,代码来源:PolicyManagementServiceImpl.java

示例6: trying

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional
public ProuctTcc trying(Product product) {
	Product entity = productRepositorie.findOne(product.getId());
	entity.setNum(entity.getNum() - product.getNum());
	if (entity.getNum() < 0)
		throw new CustomException("数量不足");
	productRepositorie.save(entity);
	ProuctTcc tcc = new ProuctTcc();
	tcc.setEntityId(product.getId());
	tcc.setEntityType(2);
	tcc.setSnap("{\"num\":" + product.getNum() + "}");
	tcc.setExpire(OffsetDateTime.now().plusSeconds(expireSeconds));
	tcc.setInsTm(OffsetDateTime.now());
	tcc.setStatus(0);
	tcc.setUpdTm(OffsetDateTime.now());
	productTccRepositorie.save(tcc);
	return tcc;
}
 
开发者ID:zhaoqilong3031,项目名称:spring-cloud-samples,代码行数:19,代码来源:ProductService.java

示例7: signOut

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional
public HttpResponse signOut(HttpRequest request) {
    some(request.getCookies().get(config.getTokenName()),
            Cookie::getValue).ifPresent(
            token -> {
                UserSessionDao userSessionDao = daoProvider.getDao(UserSessionDao.class);
                UserSession thisSession = userSessionDao.selectByToken(token);
                userSessionDao.delete(thisSession);
                storeProvider.getStore(BOUNCR_TOKEN).delete(token);
            }
    );
    Cookie expire = builder(Cookie.create(config.getTokenName(), ""))
            .set(Cookie::setPath, "/")
            .set(Cookie::setMaxAge, -1)
            .build();
    Multimap<String, Cookie> cookies = Multimap.of(config.getTokenName(), expire);
    return builder(UrlRewriter.redirect(SignInController.class, "signInForm", SEE_OTHER))
            .set(HttpResponse::setCookies, cookies)
            .build();
}
 
开发者ID:kawasima,项目名称:bouncr,代码行数:21,代码来源:SignInController.java

示例8: createTemplate

import javax.transaction.Transactional; //导入依赖的package包/类
@Override
@Transactional
public void createTemplate(Integer tenantId, Collection<ShiftInfo> shifts) {
    Tenant tenant = entityManager.find(Tenant.class, tenantId);
    if (null == tenant) {
        throw new IllegalStateException("Tenant " + tenantId + " does not exist!");
    }
    ShiftTemplate old = getTemplate(tenantId);
    ShiftTemplate template = (null != old) ? old : new ShiftTemplate();
    template.setBaseDateType(new EnumOrCustom(tenantId, false, BaseDateDefinitions.WEEK_AFTER_START_DATE
            .toString()));
    long weeksInShifts = tenant.getConfiguration().getTemplateDuration();
    template.setRepeatType(new EnumOrCustom(tenantId, true, "0:" + weeksInShifts + ":0:0"));
    template.setUniversalExceptions(Collections.emptyList());
    template.setShifts(shifts.stream().collect(Collectors.toList()));
    template.setTenantId(tenantId);

    entityManager.merge(template);
}
 
开发者ID:kiegroup,项目名称:optashift-employee-rostering,代码行数:20,代码来源:ShiftRestServiceImpl.java

示例9: getTasksOfUser

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional
@Async
@Override
public Future<List<TaskDTO>> getTasksOfUser(final Long userId) {
  final CompletableFuture<List<TaskDTO>> future = new CompletableFuture<>();

  final TasksOfUserMessage.Request request = new TasksOfUserMessage.Request(userId);

  PatternsCS.ask(userSupervisorActor, request, Global.TIMEOUT).toCompletableFuture()
      .whenComplete((msg, exc) -> {
        if (exc == null) {
          future.complete(((TasksOfUserMessage.Response) msg).getTasks());
        } else {
          future.completeExceptionally(exc);
        }
      });

  return future;
}
 
开发者ID:stefanstaniAIM,项目名称:IPPR2016,代码行数:20,代码来源:ProcessServiceImpl.java

示例10: settingsPut

import javax.transaction.Transactional; //导入依赖的package包/类
@Override
@PreAuthorize("hasAuthority('hungry')")
@Transactional
public ResponseEntity<Object> settingsPut(@ApiParam(value = "User data" ,required=true ) @RequestBody Settings upUser, Errors errors) throws ApiException{
    
    if (errors.hasErrors()) 
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    
    try {
        settingsService.settingsPut(upUser);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (OptimisticLockException ex) {
        try {
            User user = settingsService.settingsGet();
            throw new ConcurrentModificationException(409, "Concurrent modification error.", user);
        } catch (ApiException ex1) {
            Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1);
            throw new ApiException(500, "Concurrent modification exception: internal error");
        }
    }  

}
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:23,代码来源:SettingsApiController.java

示例11: foodsPost

import javax.transaction.Transactional; //导入依赖的package包/类
@PreAuthorize("hasAuthority('chef')")
@Transactional
public ResponseEntity<Object> foodsPost(@ApiParam(value = "The food to save"  ) @RequestBody FoodDetails foodDetails, Errors errors)  throws ApiException, Exception {

   //       '204': Food succesfully created
   //       '400':
   //       '412':  description: Food name already exists PRECONDITION_FAILED
   //        500: Internal server error 
    if (errors.hasErrors()) {
        Error error = new Error();
        error.setError("400");
        error.setMessage("Validation Failed");
        System.out.println("" + errors.getAllErrors());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }        
   
    foodService.foodsPost(foodDetails); 
    return new ResponseEntity<>( HttpStatus.NO_CONTENT);
     
}
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:21,代码来源:FoodsApiController.java

示例12: testRegisterInvalidEmail

import javax.transaction.Transactional; //导入依赖的package包/类
@Test
@Transactional
public void testRegisterInvalidEmail() throws Exception {
    UserDTO u = new UserDTO(
        "bob",              // login
        "password",         // password
        "Bob",              // firstName
        "Green",            // lastName
        "invalid",          // e-mail <-- invalid
        true,               // activated
        "en",               // langKey
        new HashSet<>(Arrays.asList(AuthoritiesConstants.USER))
    );

    restUserMockMvc.perform(
        post("/api/register")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(u)))
        .andExpect(status().isBadRequest());

    Optional<User> user = userRepository.findOneByLogin("bob");
    assertThat(user.isPresent()).isFalse();
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:24,代码来源:AccountResourceIntTest.java

示例13: menusMonthlyMonthyearGet

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional
public List<DailyMenu> menusMonthlyMonthyearGet(String monthyear, Long userId) throws ApiException, Exception {
    String patternString = "^\\d{2}-\\d{4}$";
    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(monthyear);
    if (matcher.matches()) {
        int month = Integer.parseInt(monthyear.substring(0, 2));
        int year = Integer.parseInt(monthyear.substring(3, 7));
        if (month > 12) {
            throw new ApiException(400, "Monthly menu not found");
        }
        LocalDate monthYearDate = new LocalDate().withYear(year).withMonthOfYear(month);
        LocalDate startOfMonth = monthYearDate.dayOfMonth().withMinimumValue();
        int daysOfMonth = monthYearDate.dayOfMonth().withMaximumValue().getDayOfMonth();
        List<DailyMenu> monthlyMenu = new ArrayList<>();
        for (int i = 0; i < daysOfMonth; i++) {
            DailyMenu dailymenu = createOrderedDailyMenu(startOfMonth.plusDays(i), userId);
            if (dailymenu.getDate() != null) {
                monthlyMenu.add(dailymenu);
            }
        }
        return monthlyMenu;
    } else {
        throw new ApiException(400, "Monthly menu not found");
    }
}
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:27,代码来源:MenusService.java

示例14: userIdGet

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional
public User userIdGet(Long id) throws ApiException, Exception {
    //If id exists in database.
    if (userRepo.findById(id) != null) {
        com.jrtechnologies.yum.data.entity.User userEntity = userRepo.findById(id);
        User userModel = new User();
        UserRoleConverter userRole = new UserRoleConverter();
        LastEdit lastEdit = new LastEdit();
        lastEdit.setTimeStamp(userEntity.getLastEdit());
        lastEdit.setVersion(userEntity.getVersion());
        userModel.setId(userEntity.getId());
        userModel.setFirstName(userEntity.getFirstName());
        userModel.setLastName(userEntity.getLastName());
        userModel.setEmail(userEntity.getEmail());
        userModel.setRole(userRole.convertToDatabaseColumn(userEntity.getUserRole()));
        userModel.setRegistrationDate(userEntity.getRegistrationDate());
        userModel.setApproved(userEntity.isApproved());
        userModel.setLastEdit(lastEdit);
        userModel.setHasPicture(userEntity.hasPicture());
        userModel.setBalance(userEntity.getBalance());
        return userModel; // Return one user.
    }
    throw new ApiException(404, "User not found");
}
 
开发者ID:jrtechnologies,项目名称:yum,代码行数:25,代码来源:UsersService.java

示例15: seedUser

import javax.transaction.Transactional; //导入依赖的package包/类
@Transactional
private void seedUser() {
    String userSql = "SELECT email FROM users U WHERE U.email = \'[email protected]\' LIMIT 1";
    List<User> u = jdbcTemplate.query(userSql, (resultSet, rowNum) -> null);

    if(u == null || u.size() <= 0) {
        User user = new User();
        user.setName("admin");
        user.setEmail("[email protected]");
        user.setPassword(new BCryptPasswordEncoder().encode("password"));
        user.setEnabled(true);
        userDAOInterface.save(user);
        logger.info("Admin user seeded");
    } else {
        logger.info("Seeding not required");
    }
}
 
开发者ID:boweihan,项目名称:basic-spring-boot-server,代码行数:18,代码来源:ContextRefreshedEventListener.java


注:本文中的javax.transaction.Transactional类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。