List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:mojo.core.test.XStreamTest.java
public void testProxy() { log("Testing uninitialized hibernate collection"); Object tmp = personService.findById(person.getId()); String xml = xstream.toXML(tmp); // System.out.println("XML: " + xml); assertEmptyElement(xml, "pets"); assertEmptyElement(xml, "phones"); log("Testing uninitialized hibernate proxy"); tmp = petService.findById(pet.getId()); xml = xstream.toXML(tmp);/*from w w w. j a va 2 s.c o m*/ // System.out.println("XML: " + xml); assertEmptyElement(xml, "owner"); log("Testing initialized hibernate proxy & collection"); TransactionTemplate template = new TransactionTemplate(transactionManager); tmp = template.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { Select<Object> query = new Select<Object>(Pet.class, new ByKey(pet.getId())); Pet pet = (Pet) repository.select(query).unique(); pet.getOwner().getName(); // init proxy pet.getOwner().getPets().size(); // init collection return pet; } }); xml = xstream.toXML(tmp); // System.out.println("XML: " + xml); assertNotEmptyElement(xml, "owner"); assertNotEmptyElement(xml, "pets"); assertEmptyElement(xml, "phones"); }
From source file:com.vladmihalcea.HibernateBagMultiLevelFetchTest.java
@Test public void test() { final Long forestId = transactionTemplate.execute(new TransactionCallback<Long>() { @Override//from w w w.j av a2s . c o m public Long doInTransaction(TransactionStatus transactionStatus) { BagForest forest = new BagForest(); BagTree tree1 = new BagTree(); tree1.setIndex(0); BagBranch branch11 = new BagBranch(); branch11.setIndex(0); BagLeaf leaf111 = new BagLeaf(); leaf111.setIndex(0); BagLeaf leaf112 = new BagLeaf(); leaf111.setIndex(1); BagLeaf leaf113 = new BagLeaf(); leaf111.setIndex(2); BagLeaf leaf114 = new BagLeaf(); leaf111.setIndex(3); branch11.addLeaf(leaf111); branch11.addLeaf(leaf112); branch11.addLeaf(leaf113); branch11.addLeaf(leaf114); BagBranch branch12 = new BagBranch(); branch12.setIndex(1); BagLeaf leaf121 = new BagLeaf(); leaf121.setIndex(1); BagLeaf leaf122 = new BagLeaf(); leaf122.setIndex(2); BagLeaf leaf123 = new BagLeaf(); leaf123.setIndex(3); BagLeaf leaf124 = new BagLeaf(); leaf124.setIndex(4); branch12.addLeaf(leaf121); branch12.addLeaf(leaf122); branch12.addLeaf(leaf123); branch12.addLeaf(leaf124); tree1.addBranch(branch11); tree1.addBranch(branch12); BagTree tree2 = new BagTree(); tree2.setIndex(1); BagBranch branch21 = new BagBranch(); branch21.setIndex(0); BagLeaf leaf211 = new BagLeaf(); leaf211.setIndex(0); BagLeaf leaf212 = new BagLeaf(); leaf111.setIndex(1); BagLeaf leaf213 = new BagLeaf(); leaf111.setIndex(2); BagLeaf leaf214 = new BagLeaf(); leaf111.setIndex(3); branch21.addLeaf(leaf211); branch21.addLeaf(leaf212); branch21.addLeaf(leaf213); branch21.addLeaf(leaf214); BagBranch branch22 = new BagBranch(); branch22.setIndex(2); BagLeaf leaf221 = new BagLeaf(); leaf121.setIndex(0); BagLeaf leaf222 = new BagLeaf(); leaf121.setIndex(1); BagLeaf leaf223 = new BagLeaf(); leaf121.setIndex(2); branch22.addLeaf(leaf221); branch22.addLeaf(leaf222); branch22.addLeaf(leaf223); tree2.addBranch(branch21); tree2.addBranch(branch22); forest.addTree(tree1); forest.addTree(tree2); entityManager.persist(forest); entityManager.flush(); return forest.getId(); } }); BagForest forest = transactionTemplate.execute(new TransactionCallback<BagForest>() { @Override public BagForest doInTransaction(TransactionStatus transactionStatus) { return entityManager.find(BagForest.class, forestId); } }); try { navigateForest(forest); fail("Should have thrown LazyInitializationException!"); } catch (LazyInitializationException expected) { } forest = transactionTemplate.execute(new TransactionCallback<BagForest>() { @Override public BagForest doInTransaction(TransactionStatus transactionStatus) { BagForest forest = entityManager.find(BagForest.class, forestId); navigateForest(forest); return forest; } }); try { forest = transactionTemplate.execute(new TransactionCallback<BagForest>() { @Override public BagForest doInTransaction(TransactionStatus transactionStatus) { BagForest forest = entityManager .createQuery( "select f " + "from BagForest f " + "join fetch f.trees t " + "join fetch t.branches b " + "join fetch b.leaves l ", BagForest.class) .getSingleResult(); return forest; } }); fail("Should have thrown MultipleBagFetchException!"); } catch (PersistenceException expected) { assertEquals(MultipleBagFetchException.class, expected.getCause().getClass()); } List<BagLeaf> leaves = transactionTemplate.execute(new TransactionCallback<List<BagLeaf>>() { @Override public List<BagLeaf> doInTransaction(TransactionStatus transactionStatus) { List<BagLeaf> leaves = entityManager .createQuery("select l " + "from BagLeaf l " + "inner join fetch l.branch b " + "inner join fetch b.tree t " + "inner join fetch t.forest f " + "where f.id = :forestId", BagLeaf.class) .setParameter("forestId", forestId).getResultList(); return leaves; } }); forest = reconstructForest(leaves, forestId); navigateForest(forest); final BagBranch firstBranch = forest.getTrees().get(0).getBranches().get(0); firstBranch.getLeaves().clear(); final BagForest toMergeForest = forest; transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { BagForest savedForest = entityManager.merge(toMergeForest); if (!firstBranch.getLeaves() .equals(savedForest.getTrees().get(0).getBranches().get(0).getLeaves())) { LOG.error("Unsafe reusing the bag, changes haven't propagated!"); } entityManager.flush(); return null; } }); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { BagForest savedForest = entityManager.find(BagForest.class, forestId); if (!firstBranch.getLeaves() .equals(savedForest.getTrees().get(0).getBranches().get(0).getLeaves())) { LOG.error("Unsafe reusing the bag, changes haven't propagated!"); } return null; } }); }
From source file:fr.mycellar.interfaces.facades.stack.StackServiceFacadeImpl.java
@Override public synchronized void onThrowable(final Throwable throwable) { // The transaction must be inside the lock. So we must use a transaction // template and not the Transactional annotation. TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transactionTemplate.setReadOnly(false); transactionTemplate.execute(new TransactionCallback<Object>() { @Override//from w ww .j a v a2 s .c o m public Object doInTransaction(TransactionStatus status) { stackService.onThrowable(throwable); return null; } }); }
From source file:org.iti.agrimarket.model.dao.ProductDAO.java
@Override public void destroy(Integer id) { Product product = findProduct(id);/*from w w w . ja v a 2 s .c om*/ transactionTemplate.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus ts) { try { Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); session.delete(product); return true; } catch (Exception e) { e.printStackTrace(); ts.setRollbackOnly(); } return false; } }); }
From source file:org.statefulj.demo.ddd.notification.domain.impl.NotificationServiceImpl.java
@PostConstruct private void init() { TransactionTemplate tt = new TransactionTemplate(transactionManager); tt.execute(new TransactionCallback<Object>() { @Override/* w w w . j a v a2s .c om*/ public Object doInTransaction(TransactionStatus status) { return entityManager .createNativeQuery("CREATE SEQUENCE notification_sequence AS BIGINT START WITH 1") .executeUpdate(); } }); }
From source file:com.opensymphony.able.filter.SimpleTransactionServletFilter.java
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { // TODO we could get clever and figure out what URIs are read only transactions etc final TransactionTemplate transactionTemplate = (TransactionTemplate) context .getBean("transactionTemplate"); transactionTemplate.setReadOnly(false); if (log.isDebugEnabled()) { log.debug("Starting a transaction"); }/* w w w.ja v a 2 s. co m*/ try { Exception e = (Exception) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { TransactionOutcome outcome = new TransactionOutcome(status, transactionTemplate); TransactionOutcome.setTransactionOutcome(outcome); filterChain.doFilter(request, response); if (outcome.isRollbackOnly()) { log.debug("Outcome is rollback"); status.setRollbackOnly(); } if (log.isDebugEnabled()) { log.debug("Completing a transaction with rollback: " + status.isRollbackOnly()); } return null; } catch (RuntimeException e) { throw e; } catch (Exception e) { return e; } } }); if (log.isDebugEnabled()) { log.debug("End transaction with exception: " + e); } if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof ServletException) { throw (ServletException) e; } else if (e != null) { throw new ServletException(e); } } catch (TransactionException e) { Throwable cause = e.getCause(); if (cause.getCause() != null) { cause = cause.getCause(); } ; if (cause instanceof JDBCException) { JDBCException jdbcException = (JDBCException) cause; SQLException sqlException = jdbcException.getSQLException(); throw new ServletException("Failed to execute: " + jdbcException.getSQL() + ": error: " + sqlException.getSQLState() + ". Reason: " + sqlException, sqlException); } throw new ServletException(cause); } finally { TransactionOutcome.setTransactionOutcome(null); } }
From source file:nz.geek.caffe.hdb.hibernate.demo.TestEmployee.java
/** *//*w w w. ja v a 2 s. co m*/ @Test public void testHdb() { final String name = "Timmi Tester"; final Integer id = this.transactionTemplate.execute(new TransactionCallback<Integer>() { public Integer doInTransaction(TransactionStatus status) { final Employee e = new Employee(); e.setName(name); TestEmployee.this.template.save(e); return Integer.valueOf(e.getId()); } }); final Employee employee = this.template.get(Employee.class, id); Assert.assertEquals(name, employee.getName()); }
From source file:org.iti.agrimarket.model.dao.UserDAO.java
/** * @author Amr//from w ww . j av a 2s . c om * @param user * @return user Id */ @Override public int edit(User user) { return (int) transactionTemplate.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus ts) { try { Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); System.out.println("user data are : " + user.toString()); User dbUser = (User) session.load(User.class, user.getId()); if (dbUser != null) { session.update(user); return user.getId(); } return -2; } catch (HibernateException e) { e.printStackTrace(); ts.setRollbackOnly(); return -2; //means DB error } catch (Exception e) { e.printStackTrace(); ts.setRollbackOnly(); return -1; //means Server error } } }); }
From source file:me.doshou.admin.monitor.web.controller.SQLExecutorController.java
@PageableDefaults(pageNumber = 0, value = 10) @RequestMapping(value = "/sql", method = RequestMethod.POST) public String executeQL(final @RequestParam("sql") String sql, final Model model, final Pageable pageable) { model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em)); String lowerCaseSQL = sql.trim().toLowerCase(); final boolean isDML = lowerCaseSQL.startsWith("insert") || lowerCaseSQL.startsWith("update") || lowerCaseSQL.startsWith("delete"); final boolean isDQL = lowerCaseSQL.startsWith("select"); if (!isDML && !isDQL) { model.addAttribute(Constants.ERROR, "SQL????insert?update?delete?select"); return showSQLForm(); }//from w w w .j av a2 s.c o m try { new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { if (isDML) { Query query = em.createNativeQuery(sql); int updateCount = query.executeUpdate(); model.addAttribute("updateCount", updateCount); } else { String findSQL = sql; String countSQL = "select count(*) count from (" + findSQL + ") o"; Query countQuery = em.createNativeQuery(countSQL); Query findQuery = em.createNativeQuery(findSQL); findQuery.setFirstResult(pageable.getOffset()); findQuery.setMaxResults(pageable.getPageSize()); Page page = new PageImpl(findQuery.getResultList(), pageable, ((BigInteger) countQuery.getSingleResult()).longValue()); model.addAttribute("resultPage", page); em.unwrap(Session.class).doWork(new Work() { @Override public void execute(final Connection connection) throws SQLException { PreparedStatement psst = connection.prepareStatement(sql); ResultSetMetaData metaData = psst.getMetaData(); List<String> columnNames = Lists.newArrayList(); for (int i = 1, l = metaData.getColumnCount(); i <= l; i++) { columnNames.add(metaData.getColumnLabel(i)); } psst.close(); model.addAttribute("columnNames", columnNames); } }); } return null; } }); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); model.addAttribute(Constants.ERROR, sw.toString()); } return showSQLForm(); }