List of usage examples for org.hibernate.criterion DetachedCriteria getExecutableCriteria
public Criteria getExecutableCriteria(Session session)
From source file:org.jspresso.framework.application.startup.development.AbstractHibernateTestDataPersister.java
License:Open Source License
/** * Query entities by criteria.//from ww w.ja v a 2 s. c o m * * @param criteria * the Hibernate detached criteria. * @return the entity list. */ protected List<?> findByCriteria(DetachedCriteria criteria) { return criteria.getExecutableCriteria(getHibernateSession()).list(); }
From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java
License:Open Source License
/** * Tests the use of nested transactions. *//*w w w .ja v a 2s . co m*/ @Test public void testNestedTransactions() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); final TransactionTemplate tt = hbc.getTransactionTemplate(); Serializable empId = tt.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus status) { TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus nestedStatus) { DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class); Employee emp = hbc.findFirstByCriteria(empCrit, null, Employee.class); emp.setFirstName("Committed"); return emp.getId(); } }); // asserts that UOW is still active after the end of the nested transaction. assertTrue("UOW should still be active since outer TX is ongoing.", hbc.isUnitOfWorkActive()); // forces rollback of outer TX. status.setRollbackOnly(); return id; } }); DetachedCriteria empById = DetachedCriteria.forClass(Employee.class); empById.add(Restrictions.eq(IEntity.ID, empId)); Employee emp = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class); assertTrue("Inner transaction should have been committed", "Committed".equals(emp.getFirstName())); Serializable emp2Id = tt.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus status) { TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus nestedStatus) { DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class); Employee emp2 = hbc.findFirstByCriteria(empCrit, null, Employee.class); emp2.setFirstName("Rollbacked"); return emp2.getId(); } }); // forces rollback of outer TX. status.setRollbackOnly(); return id; } }); DetachedCriteria emp2ById = DetachedCriteria.forClass(Employee.class); emp2ById.add(Restrictions.eq(IEntity.ID, emp2Id)); Employee emp2 = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class); assertFalse("Inner transaction should have been rollbacked", "Rollbacked".equals(emp2.getFirstName())); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { City newCity = hbc.getEntityFactory().createEntityInstance(City.class); newCity.setName("Test City"); TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); String testZip = nestedTT.execute(new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus nestedStatus) { return "12345"; } }); newCity.setZip(testZip); hbc.registerForUpdate(newCity); } }); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { final City randomCity = hbc.findFirstByCriteria(DetachedCriteria.forClass(City.class), EMergeMode.MERGE_KEEP, City.class); TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); nestedTT.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus nestedStatus) { DetachedCriteria cityById = DetachedCriteria.forClass(City.class); cityById.add(Restrictions.eq(IEntity.ID, randomCity.getId())); City innerRandomCity = (City) cityById.getExecutableCriteria(hbc.getHibernateSession()) .uniqueResult(); // If we reach this point without exception, there is no mix between the inner TX and the outer UOW. // See bug #1118 } }); } }); }
From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java
License:Open Source License
/** * Tests sanity check on linked components. See bug #846. *///from w w w . ja va 2 s . co m @Test(expected = BackendException.class) public void testSanityChecksOnComponents() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); final TransactionTemplate tt = hbc.getTransactionTemplate(); Employee emp = tt.execute(new TransactionCallback<Employee>() { /** * {@inheritDoc} */ @Override public Employee doInTransaction(TransactionStatus status) { DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class); return (Employee) empCrit.getExecutableCriteria(hbc.getHibernateSession()).list().iterator().next(); } }); // From here, any modification on employee should result in an exception // since this instance of employee is not merged in session. // The exception should also occur on component (contact) properties // modification. emp.getContact().setAddress("test"); }
From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java
License:Open Source License
/** * Tests in TX collection element update with // optimistic locking. *///from ww w . j a v a 2s . c o m @Test public void testInTXCollectionElementUpdate() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); final AtomicInteger countDown = new AtomicInteger(10); ExecutorService es = Executors.newFixedThreadPool(countDown.get()); List<Future<Set<String>>> futures = new ArrayList<Future<Set<String>>>(); for (int t = countDown.intValue(); t > 0; t--) { futures.add(es.submit(new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { final HibernateBackendController threadHbc = getApplicationContext() .getBean("applicationBackController", HibernateBackendController.class); final TransactionTemplate threadTT = threadHbc.getTransactionTemplate(); threadHbc.start(hbc.getLocale(), hbc.getClientTimeZone()); threadHbc.setApplicationSession(hbc.getApplicationSession()); BackendControllerHolder.setThreadBackendController(threadHbc); return threadTT.execute(new TransactionCallback<Set<String>>() { /** * {@inheritDoc} */ @Override public Set<String> doInTransaction(TransactionStatus status) { DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class); Set<String> names = new HashSet<String>(); Company c = (Company) compCrit.getExecutableCriteria(threadHbc.getHibernateSession()) .list().iterator().next(); synchronized (countDown) { countDown.decrementAndGet(); // wait for all threads to arrive here so that we are sure they // have all read the same data. try { countDown.wait(); } catch (InterruptedException ex) { throw new BackendException("Test has been interrupted"); } } if (c.getName().startsWith("TX_")) { throw new BackendException("Wrong data read from DB"); } c.setName("TX_" + Long.toHexString(System.currentTimeMillis())); names.add(c.getName()); for (Department d : c.getDepartments()) { d.setName(Long.toHexString(System.currentTimeMillis())); names.add(d.getName()); } return names; } }); } })); } while (countDown.get() > 0) { try { Thread.sleep(200); } catch (InterruptedException ex) { throw new BackendException("Test has been interrupted"); } } synchronized (countDown) { countDown.notifyAll(); } int successfullTxCount = 0; Set<String> names = new HashSet<String>(); for (Future<Set<String>> f : futures) { try { names = f.get(); successfullTxCount++; } catch (Exception ex) { if (ex.getCause() instanceof OptimisticLockingFailureException) { // safely ignore since this is what we are testing. } else { throw new BackendException(ex); } } } es.shutdown(); assertTrue("Only 1 TX succeeded", successfullTxCount == 1); DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class); Company c = hbc.findFirstByCriteria(compCrit, EMergeMode.MERGE_LAZY, Company.class); assertTrue("the company name is the one of the successfull TX", names.contains(c.getName())); for (Department d : c.getDepartments()) { assertTrue("the department name is the one of the successfull TX", names.contains(d.getName())); } }
From source file:org.kimios.kernel.dms.hibernate.HWorkflowStatusFactory.java
License:Open Source License
public WorkflowStatus getEndWorkflowStatus(Workflow wf) throws ConfigException, DataSourceException { try {/*from w w w .j av a 2 s. co m*/ //Pas de successeur DetachedCriteria successorList = DetachedCriteria.forClass(WorkflowStatus.class) .add(Restrictions.isNull("successorUid")).add(Restrictions.eq("workflowUid", wf.getUid())); WorkflowStatus end = (WorkflowStatus) successorList.getExecutableCriteria(getSession()).uniqueResult(); return end; } catch (HibernateException he) { throw new DataSourceException(he); } }
From source file:org.kimios.kernel.dms.hibernate.HWorkflowStatusFactory.java
License:Open Source License
public WorkflowStatus getStartWorkflowStatus(Workflow wf) throws ConfigException, DataSourceException { try {/* w ww .j a v a2 s. co m*/ //Liste des successeurs DetachedCriteria successorList = DetachedCriteria.forClass(WorkflowStatus.class) .add(Restrictions.isNotNull("successorUid")).add(Restrictions.eq("workflowUid", wf.getUid())); List<WorkflowStatus> lSList = successorList.getExecutableCriteria(getSession()).list(); //Liste des status List<WorkflowStatus> list = getSession().createCriteria(WorkflowStatus.class) .add(Restrictions.eq("workflowUid", wf.getUid())).list(); //Not In list.removeAll(lSList); return list.get(0); } catch (HibernateException he) { throw he; } }
From source file:org.LexGrid.LexBIG.caCore.applicationservice.impl.LexEVSApplicationServiceImpl.java
License:Open Source License
@DataServiceSecurityTokenRequired public <E> List<E> query(DetachedCriteria detachedCriteria, QueryOptions queryOptions) throws ApplicationException { CriteriaImpl crit = (CriteriaImpl) detachedCriteria.getExecutableCriteria(null); String targetClassName = crit.getEntityOrClassName(); return privateQuery(detachedCriteria, targetClassName, queryOptions); }
From source file:org.LexGrid.LexBIG.caCore.dao.orm.LexEVSDAOImpl.java
License:Open Source License
protected HibernateCallback getExecuteCountCriteriaHibernateCallback(final DetachedCriteria criteria) { HibernateCallback callBack = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria exeCriteria = criteria.getExecutableCriteria(session); // Cast to CriteriaImpl to get access to the Projection and ResultTransformer CriteriaImpl cImpl = (CriteriaImpl) exeCriteria; cImpl.setFirstResult(0);//from w w w.j a va 2 s.com cImpl.setFetchSize(0); int totalElements = 0; exeCriteria.setProjection(Projections.rowCount()); List resultList = exeCriteria.list(); for (Object object : resultList) { Integer countResult = (Integer) object; totalElements += countResult; } return totalElements; } }; return callBack; }
From source file:org.LexGrid.LexBIG.caCore.dao.orm.LexEVSDAOImpl.java
License:Open Source License
protected HibernateCallback getExecuteFindQueryCriteriaHibernateCallback(final DetachedCriteria criteria, final boolean lazyLoad, final int firstResult, final int maxResults) { HibernateCallback callBack = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria query = criteria.getExecutableCriteria(session); query.setFirstResult(firstResult); query.setMaxResults(maxResults); List returnList = query.list(); if (!lazyLoad) { LexEVSDAOImpl.initializeAll(returnList); }/*from ww w . ja va 2s. c o m*/ return returnList; } }; return callBack; }
From source file:org.molasdin.wbase.hibernate.BasicHibernateEngine.java
License:Apache License
@Override public <U> List<U> invokeCriteriaForList(DetachedCriteria criteria, Class<U> clazz) { return invokeCriteriaForList(criteria.getExecutableCriteria(session()), clazz); }