本文整理汇总了Java中org.springframework.transaction.annotation.Transactional类的典型用法代码示例。如果您正苦于以下问题:Java Transactional类的具体用法?Java Transactional怎么用?Java Transactional使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Transactional类属于org.springframework.transaction.annotation包,在下文中一共展示了Transactional类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createBrand
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Test
@Transactional
public void createBrand() throws Exception {
int databaseSizeBeforeCreate = brandRepository.findAll().size();
// Create the Brand
restBrandMockMvc.perform(post("/api/brands")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(brand)))
.andExpect(status().isCreated());
// Validate the Brand in the database
List<Brand> brandList = brandRepository.findAll();
assertThat(brandList).hasSize(databaseSizeBeforeCreate + 1);
Brand testBrand = brandList.get(brandList.size() - 1);
assertThat(testBrand.getName()).isEqualTo(DEFAULT_NAME);
assertThat(testBrand.getStartDate()).isEqualTo(DEFAULT_START_DATE);
}
示例2: saveGraph
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Override
@Transactional(readOnly=false)
public long saveGraph(String graphName) {
Object[] args = new Object[1];
args[0] = graphName;
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", graphName);
MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(params);
KeyHolder keyHolder = new GeneratedKeyHolder();
getNamedParameterJdbcTemplate().update("INSERT INTO " + schema + "waygraphs (name) VALUES (:name)",
sqlParameterSource, keyHolder, new String[] {"id"});
return Long.class.cast(keyHolder.getKey());
}
示例3: create
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Transactional
public User create(String tenantSchema, final User user) {
final String sql = MessageFormat.format(TENANT_SQL_TEMPLATE, tenantSchema, "insert into user(name,password) values(?,?)");
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
return ps;
}
}, holder);
int newUserId = holder.getKey().intValue();
user.setId(newUserId);
return user;
}
示例4: deleteXmEntity
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Test
@Transactional
public void deleteXmEntity() throws Exception {
// Initialize the database
xmEntityService.save(xmEntity);
int databaseSizeBeforeDelete = xmEntityRepository.findAll().size();
// Get the xmEntity
restXmEntityMockMvc.perform(delete("/api/xm-entities/{id}", xmEntity.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean xmEntityExistsInEs = xmEntitySearchRepository.exists(xmEntity.getId());
assertThat(xmEntityExistsInEs).isFalse();
// Validate the database is empty
List<XmEntity> xmEntityList = xmEntityRepository.findAll();
assertThat(xmEntityList).hasSize(databaseSizeBeforeDelete - 1);
}
示例5: deleteDepartment
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Test
@Transactional
public void deleteDepartment() throws Exception {
// Initialize the database
departmentRepository.saveAndFlush(department);
int databaseSizeBeforeDelete = departmentRepository.findAll().size();
// Get the department
restDepartmentMockMvc.perform(delete("/api/departments/{id}", department.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Department> departmentList = departmentRepository.findAll();
assertThat(departmentList).hasSize(databaseSizeBeforeDelete - 1);
}
示例6: deleteTaskWithUser
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser(username="[email protected]",authorities={"ROLE_USER"}, password = "user")
public void deleteTaskWithUser() throws Exception {
// Initialize the database
taskRepository.saveAndFlush(taskUser);
int databaseSizeBeforeDelete = taskRepository.findAll().size();
// Get the task
restTaskMockMvc.perform(delete("/api/tasks/{id}", taskUser.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeDelete - 1);
}
示例7: addShoppingListToUserByName
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
/**
* Add new shopping list for a given user
*
* @param userName
* name of the user for which to create the new list
* @param newListName
* name of the new list
* @return newly created list
* @throws UserNotFoundException
* if user with given name doesn't exist
* @throws ListTooLongException if size of the list containing ShoppingLists would exceed limit of Short type after adding new ShoppingList
*/
@PreAuthorize("hasRole('USER')")
@Transactional(readOnly = false)
public ShoppingList addShoppingListToUserByName(String userName, String newListName) {
LOGGER.debug("addShoppingListToUserByName: user: {}, listName: {}", userName, newListName);
AppUser user = getUser(userName); //throws UserNotFoundException
// get count of user lists
short count = shoppingListRepository.countByOwnerName(userName);
if (count == Short.MAX_VALUE)
throw new ListTooLongException(ListTooLongException.listType.SHOPPING_LIST, user.getId());
count++;
ShoppingList list = user.addShoppingList(newListName, count);
list = shoppingListRepository.save(list);
LOGGER.info("addShoppingListToUserByName: Created new list: {}", list);
return list;
}
示例8: update
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SysUserEntity user) throws Exception {
if (StringUtils.isBlank(user.getPassword())) {
user.setPassword(null);
} else {
user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
}
sysUserDao.update(user);
//检查角色是否越权
checkRole(user);
//保存用户与角色关系
sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
}
示例9: create
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Transactional
public long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus)
throws ShepherException {
if (creator == null) {
throw ShepherException.createIllegalParameterException();
}
Stat stat = nodeDAO.getStat(cluster, path, true);
long snapshotId = snapshotBiz.getOriginalId(path, cluster, ReviewUtil.DEFAULT_CREATOR, stat, action, true);
long newSnapshotId = snapshotBiz.create(cluster, path, data, creator.getName(), action, ReviewUtil.DEFAULT_MTIME,
ReviewStatus.NEW, stat.getVersion() + 1, ReviewUtil.DEFAULT_REVIEWER).getId();
Set<String> masters = teamBiz.listUserNamesByPathAndUser(creator.getId(), cluster, path, Role.MASTER);
String reviewers = this.asStringReviewers(masters);
long reviewId = reviewBiz.create(cluster, path, snapshotId, newSnapshotId,
reviewStatus, creator.getName(), ReviewUtil.DEFAULT_REVIEWER, action).getId();
logger.info("Create review request, reviewId={}, creator={}, reviewers={}", reviewId, creator, reviewers);
mailSenderFactory.getMailSender().noticeUpdate(masters, creator.getName(), path, cluster, serverUrl + "/reviews/" + reviewId);
return reviewId;
}
示例10: testFinishPasswordResetTooSmall
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Test
@Transactional
public void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
restMvc.perform(
post("/api/account/reset_password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
示例11: edit
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Override
@Transactional
public void edit(HierarchyTopic topic)
{
HierarchyTopic oldTopic = dao.findById(topic.getId());
ensureEditRights(oldTopic);
dao.unlinkFromSession(oldTopic);
topic.setListPosition(oldTopic.getListPosition());
dao.deleteAny(oldTopic.getName());
dao.deleteAny(oldTopic.getShortDescription());
dao.deleteAny(oldTopic.getLongDescription());
dao.deleteAny(oldTopic.getResultsSectionName());
dao.deleteAny(oldTopic.getSubtopicsSectionName());
dao.saveOrUpdate(topic);
}
示例12: testUpdate
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Test
@Transactional
public void testUpdate() {
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("tom");
JpaUtil.persist(user);
user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("lisi");
JpaUtil.persist(user);
Linu linu = JpaUtil.linu(User.class);
linu.equal("name", "lisi").set("name", "kevin");
Assert.isTrue(linu.update() == 1, "Not Success.");
JpaUtil.removeAll(User.class);
}
示例13: bindAgent
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Override
@Transactional(rollbackFor=Exception.class)
public boolean bindAgent(Integer appId, String appAgentList) {
if (null == appId) {
return false;
}
String[] arr = appAgentList.split(",");
for(String appAgent: arr){
String[] info = appAgent.split("[_]");
if(info==null||info.length!=2){
continue;
}
AppAgent app =new AppAgent();
app.setAppId(appId);
app.setIp(info[0].trim());
app.setAssetId(info[1].trim());
supervisorDao.addAppAgent(app);
}
noticeHeartbeat();
return true;
}
示例14: addJobTrigger
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Transactional
@Override
public boolean addJobTrigger(ScheduleJobEntity job) {
try {
Scheduler scheduler = schedulerFactoryBean.getScheduler();
// 表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
.cronSchedule(job.getCronExpression());
// 按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = newTrigger()
.forJob(job.getJobKey()) //绑定job
.withIdentity(job.getTriggerKey())
.startAt(job.getStartDate()) // job开始日期
.endAt(job.getEndDate())// job结束日期
.withSchedule(scheduleBuilder).build();
// 将trigger添加到quartz的scheduler容器
scheduler.scheduleJob(trigger);
return Boolean.TRUE;
} catch (SchedulerException e) {
throw new ServiceException(e);
}
}
示例15: getSubscriptionsForGraph
import org.springframework.transaction.annotation.Transactional; //导入依赖的package包/类
@Override
@Transactional(readOnly=true)
public List<ISubscription> getSubscriptionsForGraph(String graphName, String groupName) {
if (groupName == null) {
return getSubscriptionsForGraph(graphName);
} else {
Object[] args = new Object[2];
args[0] = graphName;
args[1] = groupName;
// <graphName> => lies waygraphs => <graph_id> => lies subscription_groups => <group_id> => lies subscriptions
return getJdbcTemplate().query("SELECT s.*, sg.name AS group_name, sg.graph_id AS group_graph_id, wg.name AS graph_name " +
"FROM " + schema + "subscriptions AS s, " +
schema + "subscription_groups AS sg " +
"LEFT JOIN " + schema + "waygraphs AS wg ON sg.graph_id = wg.id " +
"WHERE s.group_id = sg.id AND sg.graph_id = (SELECT w.id FROM " + schema + "waygraphs AS w WHERE name = ?) " +
"AND sg.name = ?",
args, subscriptionRowMapper);
}
}