當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。