Java Code Examples for org.hibernate.Session#refresh()
The following examples show how to use
org.hibernate.Session#refresh() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HibernateCriteriaIntegrationTest.java From tutorials with MIT License | 6 votes |
@Test public void givenNewItemPrice_whenCriteriaUpdate_thenReturnAffectedResult() { int oldPrice = 10, newPrice = 20; Session session = HibernateUtil.getHibernateSession(); Item item = new Item(12, "Test Item 12", "This is a description"); item.setItemPrice(oldPrice); session.save(item); CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaUpdate<Item> criteriaUpdate = cb.createCriteriaUpdate(Item.class); Root<Item> root = criteriaUpdate.from(Item.class); criteriaUpdate.set("itemPrice", newPrice); criteriaUpdate.where(cb.equal(root.get("itemPrice"), oldPrice)); Transaction transaction = session.beginTransaction(); session.createQuery(criteriaUpdate).executeUpdate(); transaction.commit(); Item updatedItem = session.createQuery("FROM Item WHERE itemPrice = " + newPrice, Item.class).getSingleResult(); session.refresh(updatedItem); assertEquals(newPrice, updatedItem.getItemPrice().intValue()); }
Example 2
Source File: TransactionalTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.get(ItemTransactional.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 3
Source File: TransactionalTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.get(ItemTransactional.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 4
Source File: TransactionalTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.get(ItemTransactional.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 5
Source File: TransactionalTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.get(ItemTransactional.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 6
Source File: ReadWriteTest.java From redisson with Apache License 2.0 | 5 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemReadWrite item = new ItemReadWrite( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); Assert.assertEquals("data", item.getName()); s.delete(item); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 7
Source File: AssignmentRepositoryImpl.java From sakai with Educational Community License v2.0 | 5 votes |
@Override @Transactional public void deleteSubmission(String submissionId) { Session session = sessionFactory.getCurrentSession(); AssignmentSubmission submission = (AssignmentSubmission) session.get(AssignmentSubmission.class, submissionId); if (submission != null) { log.info("Deleting submission {}", submission); Assignment assignment = submission.getAssignment(); // must call refresh here to ensure the collections are initialized before changing, this is due to lazy loaded entities session.refresh(assignment); assignment.getSubmissions().remove(submission); session.update(assignment); session.flush(); } }
Example 8
Source File: ReadWriteTest.java From redisson with Apache License 2.0 | 5 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemReadWrite item = new ItemReadWrite( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); Assert.assertEquals("data", item.getName()); s.delete(item); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 9
Source File: ReadWriteTest.java From redisson with Apache License 2.0 | 5 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemReadWrite item = new ItemReadWrite( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); Assert.assertEquals("data", item.getName()); s.delete(item); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 10
Source File: ReadWriteTest.java From redisson with Apache License 2.0 | 5 votes |
@Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemReadWrite item = new ItemReadWrite( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); s = openSession(); s.beginTransaction(); item = (ItemReadWrite) s.get(ItemReadWrite.class, id); Assert.assertEquals("data", item.getName()); s.delete(item); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); }
Example 11
Source File: HibernateSessionFlushingTests.java From spring-analysis-note with MIT License | 5 votes |
@Test // SPR-16956 @Transactional(readOnly = true) public void findSamWithReadOnlySession() { Person sam = personService.findByName(SAM); sam.setName("Vlad"); // By setting setDefaultReadOnly(true), the user can no longer modify any entity... Session session = sessionFactory.getCurrentSession(); session.flush(); session.refresh(sam); assertEquals("Sam", sam.getName()); }
Example 12
Source File: AssignmentRepositoryImpl.java From sakai with Educational Community License v2.0 | 5 votes |
@Override @Transactional public void deleteSubmission(String submissionId) { Session session = sessionFactory.getCurrentSession(); AssignmentSubmission submission = (AssignmentSubmission) session.get(AssignmentSubmission.class, submissionId); if (submission != null) { log.info("Deleting submission {}", submission); Assignment assignment = submission.getAssignment(); // must call refresh here to ensure the collections are initialized before changing, this is due to lazy loaded entities session.refresh(assignment); assignment.getSubmissions().remove(submission); session.update(assignment); session.flush(); } }
Example 13
Source File: RefreshTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public void testRefreshCascade() throws Throwable { Session session = openSession(); Transaction txn = session.beginTransaction(); JobBatch batch = new JobBatch( new Date() ); batch.createJob().setProcessingInstructions( "Just do it!" ); batch.createJob().setProcessingInstructions( "I know you can do it!" ); // write the stuff to the database; at this stage all job.status values are zero session.persist( batch ); session.flush(); // behind the session's back, let's modify the statuses updateStatuses( session.connection() ); // Now lets refresh the persistent batch, and see if the refresh cascaded to the jobs collection elements session.refresh( batch ); Iterator itr = batch.getJobs().iterator(); while( itr.hasNext() ) { Job job = ( Job ) itr.next(); assertEquals( "Jobs not refreshed!", 1, job.getStatus() ); } txn.rollback(); session.close(); }
Example 14
Source File: HibernateSessionFlushingTests.java From java-technology-stack with MIT License | 5 votes |
@Test // SPR-16956 @Transactional(readOnly = true) public void findSamWithReadOnlySession() { Person sam = personService.findByName(SAM); sam.setName("Vlad"); // By setting setDefaultReadOnly(true), the user can no longer modify any entity... Session session = sessionFactory.getCurrentSession(); session.flush(); session.refresh(sam); assertEquals("Sam", sam.getName()); }
Example 15
Source File: InstructionalOfferingModifyAction.java From unitime with Apache License 2.0 | 4 votes |
/** * Update the instructional offering config * @param request * @param frm */ private void doUpdate(HttpServletRequest request, InstructionalOfferingModifyForm frm) throws Exception { // Get Instructional Offering Config InstrOfferingConfigDAO iocdao = new InstrOfferingConfigDAO(); InstrOfferingConfig ioc = iocdao.get(frm.getInstrOffrConfigId()); Session hibSession = iocdao.getSession(); // Get default room group RoomGroup rg = RoomGroup.getGlobalDefaultRoomGroup(ioc.getSession()); sessionContext.checkPermission(ioc, Right.MultipleClassSetup); Transaction tx = null; try { tx = hibSession.beginTransaction(); // If the instructional offering config limit or unlimited flag has changed update it. if (frm.isInstrOffrConfigUnlimited() != ioc.isUnlimitedEnrollment()) { ioc.setUnlimitedEnrollment(frm.isInstrOffrConfigUnlimited()); ioc.setLimit(frm.isInstrOffrConfigUnlimited() ? 0 : frm.getInstrOffrConfigLimit()); hibSession.update(ioc); } else if (!frm.getInstrOffrConfigLimit().equals(ioc.getLimit())) { ioc.setLimit(frm.getInstrOffrConfigLimit()); hibSession.update(ioc); } InstructionalMethod imeth = (frm.getInstructionalMethod() == null || frm.getInstructionalMethod() < 0 ? null : InstructionalMethodDAO.getInstance().get(frm.getInstructionalMethod(), hibSession)); if (!ToolBox.equals(ioc.getInstructionalMethod(), imeth)) { ioc.setInstructionalMethod(imeth); hibSession.update(ioc); } // Get map of subpart ownership so that after the classes have changed it is possible to see if the ownership for a subparts has changed HashMap origSubpartManagingDept = new HashMap(); if (ioc.getSchedulingSubparts() != null){ SchedulingSubpart ss = null; for (Iterator it = ioc.getSchedulingSubparts().iterator(); it.hasNext();){ ss = (SchedulingSubpart) it.next(); origSubpartManagingDept.put(ss.getUniqueId(), ss.getManagingDept()); } } // For all added classes, create the classes and save them, get back a map of the temp ids to the new classes HashMap tmpClassIdsToClasses = addClasses(frm, ioc, hibSession); // For all changed classes, update them modifyClasses(frm, ioc, hibSession, rg, tmpClassIdsToClasses); // Update subpart ownership modifySubparts(ioc, origSubpartManagingDept, rg, hibSession); // Delete all classes in the original classes that are no longer in the modified classes deleteClasses(frm, ioc, hibSession, tmpClassIdsToClasses); String className = ApplicationProperty.ExternalActionInstrOffrConfigChange.value(); ExternalInstrOffrConfigChangeAction configChangeAction = null; if (className != null && className.trim().length() > 0){ configChangeAction = (ExternalInstrOffrConfigChangeAction) (Class.forName(className).newInstance()); if (!configChangeAction.validateConfigChangeCanOccur(ioc.getInstructionalOffering(), hibSession)){ throw new Exception("Configuration change violates rules for Add On, rolling back the change."); } } ioc.getInstructionalOffering().computeLabels(hibSession); ChangeLog.addChange( hibSession, sessionContext, ioc, ChangeLog.Source.CLASS_SETUP, ChangeLog.Operation.UPDATE, ioc.getInstructionalOffering().getControllingCourseOffering().getSubjectArea(), null); tx.commit(); hibSession.flush(); hibSession.refresh(ioc); hibSession.refresh(ioc.getInstructionalOffering()); if (configChangeAction != null){ configChangeAction.performExternalInstrOffrConfigChangeAction(ioc.getInstructionalOffering(), hibSession); } } catch (Exception e) { Debug.error(e); try { if(tx!=null && tx.isActive()) tx.rollback(); } catch (Exception e1) { } throw e; } }
Example 16
Source File: TuplizerDynamicEntityTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
public void testIt() { // Test saving these dyna-proxies Session session = openSession(); session.beginTransaction(); Company company = ProxyHelper.newCompanyProxy(); company.setName( "acme" ); session.save( company ); Customer customer = ProxyHelper.newCustomerProxy(); customer.setName( "Steve" ); customer.setCompany( company ); Address address = ProxyHelper.newAddressProxy(); address.setStreet( "somewhere over the rainbow" ); address.setCity( "lawerence, kansas" ); address.setPostalCode( "toto"); customer.setAddress( address ); customer.setFamily( new HashSet() ); Person son = ProxyHelper.newPersonProxy(); son.setName( "son" ); customer.getFamily().add( son ); Person wife = ProxyHelper.newPersonProxy(); wife.setName( "wife" ); customer.getFamily().add( wife ); session.save( customer ); session.getTransaction().commit(); session.close(); assertNotNull( "company id not assigned", company.getId() ); assertNotNull( "customer id not assigned", customer.getId() ); assertNotNull( "address id not assigned", address.getId() ); assertNotNull( "son:Person id not assigned", son.getId() ); assertNotNull( "wife:Person id not assigned", wife.getId() ); // Test loading these dyna-proxies, along with flush processing session = openSession(); session.beginTransaction(); customer = ( Customer ) session.load( Customer.class, customer.getId() ); assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer ) ); customer.setName( "other" ); session.flush(); assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer.getCompany() ) ); session.refresh( customer ); assertEquals( "name not updated", "other", customer.getName() ); assertEquals( "company association not correct", "acme", customer.getCompany().getName() ); session.getTransaction().commit(); session.close(); // Test detached entity re-attachment with these dyna-proxies customer.setName( "Steve" ); session = openSession(); session.beginTransaction(); session.update( customer ); session.flush(); session.refresh( customer ); assertEquals( "name not updated", "Steve", customer.getName() ); session.getTransaction().commit(); session.close(); // Test querying session = openSession(); session.beginTransaction(); int count = session.createQuery( "from Customer" ).list().size(); assertEquals( "querying dynamic entity", 1, count ); session.clear(); count = session.createQuery( "from Person" ).list().size(); assertEquals( "querying dynamic entity", 3, count ); session.getTransaction().commit(); session.close(); // test deleteing session = openSession(); session.beginTransaction(); session.delete( company ); session.delete( customer ); session.getTransaction().commit(); session.close(); }
Example 17
Source File: InterceptorDynamicEntityTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
public void testIt() { // Test saving these dyna-proxies Session session = openSession(); session.beginTransaction(); Company company = ProxyHelper.newCompanyProxy(); company.setName( "acme" ); session.save( company ); Customer customer = ProxyHelper.newCustomerProxy(); customer.setName( "Steve" ); customer.setCompany( company ); session.save( customer ); session.getTransaction().commit(); session.close(); assertNotNull( "company id not assigned", company.getId() ); assertNotNull( "customer id not assigned", customer.getId() ); // Test loading these dyna-proxies, along with flush processing session = openSession(); session.beginTransaction(); customer = ( Customer ) session.load( Customer.class, customer.getId() ); assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer ) ); customer.setName( "other" ); session.flush(); assertFalse( "should-be-proxy was initialized", Hibernate.isInitialized( customer.getCompany() ) ); session.refresh( customer ); assertEquals( "name not updated", "other", customer.getName() ); assertEquals( "company association not correct", "acme", customer.getCompany().getName() ); session.getTransaction().commit(); session.close(); // Test detached entity re-attachment with these dyna-proxies customer.setName( "Steve" ); session = openSession(); session.beginTransaction(); session.update( customer ); session.flush(); session.refresh( customer ); assertEquals( "name not updated", "Steve", customer.getName() ); session.getTransaction().commit(); session.close(); // Test querying session = openSession(); session.beginTransaction(); int count = session.createQuery( "from Customer" ).list().size(); assertEquals( "querying dynamic entity", 1, count ); session.clear(); count = session.createQuery( "from Person" ).list().size(); assertEquals( "querying dynamic entity", 1, count ); session.getTransaction().commit(); session.close(); // test deleteing session = openSession(); session.beginTransaction(); session.delete( company ); session.delete( customer ); session.getTransaction().commit(); session.close(); }
Example 18
Source File: RoleDAOHibImpl.java From Knowage-Server with GNU Affero General Public License v3.0 | 4 votes |
/** * Erase role. * * @param aRole * the a role * @throws EMFUserError * the EMF user error * @see it.eng.spagobi.commons.dao.IRoleDAO#eraseRole(it.eng.spagobi.commons.bo.Role) */ @Override public void eraseRole(Role aRole) throws EMFUserError { Session aSession = null; Transaction tx = null; try { aSession = getSession(); tx = aSession.beginTransaction(); SbiExtRoles hibRole = (SbiExtRoles) aSession.load(SbiExtRoles.class, aRole.getId()); // deletes associations with events (and events themselves, if they // have no more associations) // Query hibQuery = // aSession.createQuery(" from SbiEventRole ser where // ser.id.role.extRoleId = " // + hibRole.getExtRoleId().toString()); // Query hibQuery = aSession.createQuery(" from SbiEventRole ser where ser.id.role.extRoleId = ?"); // hibQuery.setInteger(0, hibRole.getExtRoleId().intValue()); // List eventsRole = hibQuery.list(); // Iterator it = eventsRole.iterator(); // while (it.hasNext()) { // SbiEventRole eventRole = (SbiEventRole) it.next(); // SbiEventsLog event = eventRole.getId().getEvent(); // aSession.delete(eventRole); // aSession.flush(); // aSession.refresh(event); // Set roles = event.getRoles(); // if (roles.isEmpty()) { // aSession.delete(event); // } // } Set<SbiAuthorizationsRoles> authorizations = hibRole.getSbiAuthorizationsRoleses(); Iterator itf = authorizations.iterator(); while (itf.hasNext()) { SbiAuthorizationsRoles fr = (SbiAuthorizationsRoles) itf.next(); aSession.delete(fr); aSession.flush(); aSession.refresh(hibRole); } aSession.delete(hibRole); tx.commit(); } catch (HibernateException he) { logException(he); if (tx != null) tx.rollback(); throw new EMFUserError(EMFErrorSeverity.ERROR, 100); } finally { if (aSession != null) { if (aSession.isOpen()) { aSession.close(); logger.debug("The [eraseRole] occurs. Role cache will be cleaned."); this.clearCache(); } } } }
Example 19
Source File: _BaseRootDAO.java From unitime with Apache License 2.0 | 2 votes |
/** * Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement * long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances. */ public void refresh(T obj, Session s) { s.refresh(obj); }