下面列出了org.springframework.web.bind.annotation.PutMapping#org.springframework.transaction.annotation.Transactional 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
/**
* 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;
}
@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();
}
}
@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;
}
@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));
}
@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;
}
/**
* 事务控制在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 ;
}
@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;
}
@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);
}
@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);
}
@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);
}
/**
* 根据用户名称查询粉丝数量
* @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;
}
/**
* 新增添加部门
*
* @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();
}
@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()));
}
@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;
}
/**
* 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);
}
/**
* 根据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;
}
@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");
}
@Test
@Transactional
@WithMockUser("save-existing-email")
public void testSaveExistingEmail() throws Exception {
User user = new User();
user.setLogin("save-existing-email");
user.setEmail("save[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]");
}
@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();
}
@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;
}
@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());
}
}
/**
* 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);
}
@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;
}
@Before
@Transactional
public void beforeTestCase() {
log.debug("===================before test=====================");
conferenceDao.deleteAll();
}
@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;
}
@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);
}
@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;
}
@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;
}
@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));
}
如果文章对你有帮助,欢迎点击上方按钮打赏作者