本文整理汇总了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;
}
示例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);
}
示例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();
}
示例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());
}
}
}
示例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);
}
示例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;
}
示例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();
}
示例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);
}
示例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;
}
示例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");
}
}
}
示例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);
}
示例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();
}
示例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");
}
}
示例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");
}
示例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");
}
}