List of usage examples for org.hibernate Session buildLockRequest
LockRequest buildLockRequest(LockOptions lockOptions);
From source file:gr.interamerican.bo2.impl.open.hibernate.AbstractHibernateDetachStrategy.java
License:Open Source License
/** * Internal implementation//from w ww . ja va 2 s . co m * * @param object * @param provider * @param forUpdate */ @SuppressWarnings("nls") private void reattach(Object object, Provider provider, boolean forUpdate) { if (object == null) { return; } if (!(object instanceof PersistentObject)) { return; } boolean objectIsTransient = HibernateBo2Utils.isTransient((PersistentObject<?>) object); HibernateSessionProvider hProv = HibernateBo2Utils.getHibernateSessionProvider(object, provider); if (hProv == null) { return; } Session session = hProv.getHibernateSession(); Set<Object> objectsToReattachManually = new HashSet<Object>(); Set<Object> transientObjects = new HashSet<Object>(); if (object instanceof AbstractBasePo) { PoReattachAnalysisResult poInspectionResult = PoReattachAnalysis.get() .execute((AbstractBasePo<?>) object); objectsToReattachManually = poInspectionResult.getPosToReattachManually(); transientObjectsOnLastReattach = poInspectionResult.getTransientPos(); if (!objectIsTransient) { //If the original object is transient we will not care for transient Child objects transientObjects = poInspectionResult.getTransientPos(); //set lastModifiedBy to all transient children of a non-transient PO being reattached before #doReattach() runs. for (Object o : transientObjects) { setLastModifiedBy(o); } } } LOGGER.debug("--->reattach " + object.getClass().getName() + object.toString()); if (!HibernateBo2Utils.isTransient((PersistentObject<?>) object)) { try { boolean mayLockOrUpdate = mayLockOrUpdate(object, session); if (mayLockOrUpdate) { doReattach(object, session); } } catch (HibernateException he) { throw new RuntimeException(he); } hProv.register(object); } /* * Detach transient objects on the graph that were possibly * attached by a cascade option during #doReattach execution. */ int j = 0; for (Object obj : transientObjects) { if (forUpdate) { break; //do not detach transient objects if a db update will happen in this unit of work } boolean detachTransientObjectAttachedByCascade = detachTransientObjectAttachedByCascade(obj, session); if (detachTransientObjectAttachedByCascade) { LOGGER.debug("detached transient: " + obj.getClass().getName() + obj.toString()); j++; } } /* * Re-attach manually not owned associations for which there * was no cascade option during #doReattach execution. */ int i = 0; for (Object obj : objectsToReattachManually) { try { boolean mayLockOrUpdate = mayLockOrUpdate(obj, session); if (mayLockOrUpdate) { session.buildLockRequest(LockOptions.NONE).lock(obj); LOGGER.debug("reattached by locking: " + obj.getClass().getName() + obj.toString()); i++; } } catch (HibernateException he) { throw new RuntimeException(he); } } LOGGER.debug("Manual reattach candidates: " + objectsToReattachManually.size() + ". Reattached: " + i); LOGGER.debug("Transient objects: " + transientObjects.size() + ". Detached manually: " + j); LOGGER.debug("reattached " + object.getClass().getName() + object + "<---"); }
From source file:gr.interamerican.bo2.impl.open.hibernate.HibernateReadOnlyDetachStrategy.java
License:Open Source License
@Override protected void doReattach(Object object, Session session) { session.buildLockRequest(LockOptions.NONE).lock(object); }
From source file:gr.interamerican.bo2.impl.open.hibernate.TestProxySessionPropagation.java
License:Open Source License
/** * Demonstrates that a many-to-one customer instance reattached with * session.buildLockRequest(LockOptions.NONE).lock(customer) will not * have its modification record altered on the next session.flush, i.e. * no SQL associated with this entity will be sent to the database. * //from www . j a va2 s. c o m * @throws UnexpectedException * @throws DataException * @throws LogicException */ @Test public void testManyToOneNoCascadeReattachedAreNotFlushed() throws UnexpectedException, DataException, LogicException { new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { invoice = Factory.create(Invoice.class); invoice.setInvoiceNo(invoiceNo); PersistenceWorker<Invoice> ipw = openPw(Invoice.class); invoice = ipw.read(invoice); } }.execute(); new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { PoUtils.reattach(invoice, getProvider()); Customer c = invoice.getCustomer().getCustomer(); Assert.assertTrue(c instanceof HibernateProxy); HibernateProxy cProxy = (HibernateProxy) c; Assert.assertTrue(cProxy.getHibernateLazyInitializer().isUninitialized()); Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession()); c.getCustomerName(); Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized()); } }.execute(); new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { PoUtils.reattach(invoice, getProvider()); Customer c = invoice.getCustomer().getCustomer(); Assert.assertTrue(c instanceof HibernateProxy); HibernateProxy cProxy = (HibernateProxy) c; Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized()); Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession()); customerLastModified = c.getLastModified(); Session s = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$ .getHibernateSession(); s.buildLockRequest(LockOptions.NONE).lock(c); Assert.assertEquals(customerLastModified, c.getLastModified()); Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession()); c.getAddresses().size(); PersistenceWorker<Invoice> ipw = openPw(Invoice.class); ipw.store(invoice); //flush the session } }.execute(); new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { PersistenceWorker<Customer> cpw = openPw(Customer.class); Customer c = Factory.create(Customer.class); c.setCustomerNo(customerNo); c = cpw.read(c); Assert.assertEquals(customerLastModified, c.getLastModified()); } }.execute(); }
From source file:gr.interamerican.bo2.impl.open.hibernate.TestProxySessionPropagation.java
License:Open Source License
/** * Demonstrates that a many-to-one customer instance reattached with * session.buildLockRequest(LockOptions.NONE).lock(customer) will have * SQL sent on the next session.flush if it has been modified. * /*from w w w .ja va 2s .co m*/ * @throws UnexpectedException * @throws DataException * @throws LogicException */ @Test public void testDirtyManyToOneNoCascadeReattachedFlush() throws UnexpectedException, DataException, LogicException { new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { invoice = Factory.create(Invoice.class); invoice.setInvoiceNo(invoiceNo); PersistenceWorker<Invoice> ipw = openPw(Invoice.class); invoice = ipw.read(invoice); } }.execute(); new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { PoUtils.reattach(invoice, getProvider()); Customer c = invoice.getCustomer().getCustomer(); Assert.assertTrue(c instanceof HibernateProxy); HibernateProxy cProxy = (HibernateProxy) c; Assert.assertTrue(cProxy.getHibernateLazyInitializer().isUninitialized()); Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession()); c.getCustomerName(); Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized()); } }.execute(); new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { PoUtils.reattach(invoice, getProvider()); Customer c = invoice.getCustomer().getCustomer(); Assert.assertTrue(c instanceof HibernateProxy); HibernateProxy cProxy = (HibernateProxy) c; Assert.assertFalse(cProxy.getHibernateLazyInitializer().isUninitialized()); Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession()); customerLastModified = c.getLastModified(); Session s = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$ .getHibernateSession(); s.buildLockRequest(LockOptions.NONE).lock(c); Assert.assertEquals(customerLastModified, c.getLastModified()); Assert.assertNotNull(cProxy.getHibernateLazyInitializer().getSession()); c.getAddresses().size(); c.setCustomerName(customerName); //make Customer dirty PersistenceWorker<Invoice> ipw = openPw(Invoice.class); ipw.store(invoice); //flush the session } }.execute(); new AbstractBo2RuntimeCmd() { @Override public void work() throws LogicException, DataException, InitializationException, UnexpectedException { PersistenceWorker<Customer> cpw = openPw(Customer.class); Customer c = Factory.create(Customer.class); c.setCustomerNo(customerNo); c = cpw.read(c); Assert.assertEquals(customerName, c.getCustomerName()); } }.execute(); }
From source file:gr.interamerican.bo2.impl.open.hibernate.TestScenarioInvoiceHibernateOperations.java
License:Open Source License
/** * Tests re-attaching a detached UNMODIFIED instance. * //from w w w .ja v a 2 s . c om * <li>transaction1: store * <li>transaction2: read * <li>transaction3: re-attach, modify and persist * <li>transaction4: confirm operations * * @throws UnexpectedException * @throws DataException * @throws LogicException */ @Test public void testReattachToSession_unmodifiedInstance() throws UnexpectedException, DataException, LogicException { /* first, store the samples */ AbstractPersistenceOperation<Invoice> storeOp = new AbstractPersistenceOperation<Invoice>(Invoice.class) { @Override public void execute() throws LogicException, DataException { po = pw.store(po); } }; invoice = factory.sampleInvoiceFull(4); invoice.setInvoiceNo(invoiceNo); storeOp.setPo(invoice); Execute.transactional(storeOp); /* Now read them */ AbstractPersistenceOperation<Invoice> readOp = new AbstractPersistenceOperation<Invoice>(Invoice.class) { @Override public void execute() throws LogicException, DataException { invoice = pw.read(po); } }; invoice = Factory.create(Invoice.class); invoice.setInvoiceNo(invoiceNo); readOp.setPo(invoice); Execute.transactional(readOp); AbstractPersistenceOperation<Invoice> updateOp = new AbstractPersistenceOperation<Invoice>(Invoice.class) { @Override public void execute() throws LogicException, DataException { /* * re-attach with lock() * This will only work if the detached instances are unmodified. * session.update() has the same effect, but is unnecessary. */ try { Session session = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$ .getHibernateSession(); session.buildLockRequest(LockOptions.NONE).lock(invoice); } catch (InitializationException e) { fail(e.toString()); } /* add a subLine to each line. Note that subLines are proxied */ Set<InvoiceLine> lines = invoice.getLines(); for (InvoiceLine line : lines) { assertNotNull(line.getSubLines()); assertFalse(Hibernate.isInitialized(line.getSubLines())); line.getSubLines().add(factory.sampleInvoiceSubLine(line.getLineNo() + 1)); } /* persist the updated invoice */ invoice = pw.update(invoice); } }; updateOp.setPo(invoice); Execute.transactional(updateOp); /* confirm results, now each line has 2 subLines */ AbstractPersistenceOperation<Invoice> readOp2 = new AbstractPersistenceOperation<Invoice>(Invoice.class) { @Override public void execute() throws LogicException, DataException { invoice = pw.read(po); Set<InvoiceLine> lines = invoice.getLines(); for (InvoiceLine line : lines) { assertTrue(line.getSubLines().size() == 2); } } }; invoice = Factory.create(Invoice.class); invoice.setInvoiceNo(invoiceNo); readOp2.setPo(invoice); Execute.transactional(readOp2); }
From source file:gr.interamerican.bo2.impl.open.hibernate.TestScenarioInvoiceHibernateOperations.java
License:Open Source License
/** * Tests evicting an attached instance.// w ww . j a v a 2s.c om * * <li>transaction1: store * <li>transaction2: read * <li>transaction3: re-attach, modify, evict and persist * <li>transaction4: confirm operations * * @throws DataException * @throws LogicException * @throws UnexpectedException */ @Test public void testEvictingFromSession() throws DataException, LogicException, UnexpectedException { /* first, store the samples */ AbstractPersistenceOperation<Invoice> storeOp = new AbstractPersistenceOperation<Invoice>(Invoice.class) { @Override public void execute() throws LogicException, DataException { po = pw.store(po); } }; invoice = factory.sampleInvoiceFull(4); invoice.setInvoiceNo(invoiceNo); storeOp.setPo(invoice); Execute.transactional(storeOp); invoice = storeOp.getPo(); copy = factory.sampleInvoiceFull(4); copy.setInvoiceNo(copyInvoiceNo); storeOp.setPo(copy); Execute.transactional(storeOp); copy = storeOp.getPo(); /* re-attach to session, modify and update */ AbstractPersistenceOperation<Invoice> updateOp = new AbstractPersistenceOperation<Invoice>(Invoice.class) { @Override public void execute() throws LogicException, DataException { /* * re-attach with lock() * This will only work if the detached instances are unmodified. */ try { Session session = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$ .getHibernateSession(); session.buildLockRequest(LockOptions.NONE).lock(invoice); session.buildLockRequest(LockOptions.NONE).lock(copy); } catch (InitializationException e) { fail(e.toString()); } /* now that the objects are re-attached I can modify them */ invoice.getLines().add(factory.sampleInvoiceLine(5)); copy.getLines().add(factory.sampleInvoiceLine(5)); /* * evicting copy. Even though I will only explicitly update invoice, flush() will * also send SQL for the modifications of copy to the connection. If I do not want * to persist the modifications of copy, I have to evict it from the session. */ try { Session session = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$ .getHibernateSession(); session.evict(copy); } catch (InitializationException e) { fail(e.toString()); } invoice = pw.update(invoice); } }; Execute.transactional(updateOp); /* confirm results, now invoice has 5 lines and copy only 4 */ AbstractPersistenceOperation<Invoice> readOp2 = new AbstractPersistenceOperation<Invoice>(Invoice.class) { @Override public void execute() throws LogicException, DataException { po = pw.read(po); po.getLines().size(); } }; invoice = Factory.create(Invoice.class); invoice.setInvoiceNo(invoiceNo); readOp2.setPo(invoice); Execute.transactional(readOp2); invoice = readOp2.getPo(); assertTrue(invoice.getLines().size() == 5); copy = Factory.create(Invoice.class); copy.setInvoiceNo(copyInvoiceNo); readOp2.setPo(copy); Execute.transactional(readOp2); copy = readOp2.getPo(); assertTrue(copy.getLines().size() == 4); }
From source file:io.jeandavid.projects.vod.service.DvdOrderFacadeREST.java
License:Open Source License
public void doThePackaging(DvdOrder dvdOrder) { if (dvdOrder.getInternalState() != DvdOrder.PENDING) return;/* ww w . j av a2 s . c om*/ boolean pending = false; Session session = this.getSessionFactory().openSession(); session.refresh(dvdOrder); dvdOrder.switchInternalState(DvdOrder.PACKAGED); Transaction tr = session.beginTransaction(); TreeSet<DvdOrderDvd> sortedDvdOrderDvds = dvdOrder.getSortedDvdOrderDvds(); for (DvdOrderDvd dvdOrderDvd : sortedDvdOrderDvds) { Dvd dvd = (Dvd) session.load(Dvd.class, dvdOrderDvd.getDvd().getId()); LockRequest lockRequest = session.buildLockRequest(LockOptions.UPGRADE); lockRequest.lock(dvd); Integer occurenciesNumber = dvdOrderDvd.getQuantity(); if (dvd.getQuantity() >= occurenciesNumber) { dvd.setQuantity(dvd.getQuantity() - occurenciesNumber); session.saveOrUpdate(session.merge(dvd)); } else { pending = true; break; } } if (!pending) { session.saveOrUpdate(dvdOrder); session.flush(); tr.commit(); } session.close(); }
From source file:org.apacheextras.camel.component.hibernate.HibernateConsumer.java
License:Open Source License
/** * A strategy method to lock an object with an exclusive lock so that it can * be processed/*from w w w. j a v a2 s .c o m*/ * * @param entity the entity to be locked * @param session * @return true if the entity was locked */ protected boolean lockEntity(Object entity, Session session) { if (!getEndpoint().isConsumeDelete() || !getEndpoint().isConsumeLockEntity()) { return true; } try { if (LOG.isDebugEnabled()) { LOG.debug("Acquiring exclusive lock on entity: " + entity); } session.buildLockRequest(LockOptions.UPGRADE).setLockMode(LockMode.PESSIMISTIC_WRITE).setTimeOut(60000) .lock(entity); return true; } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to achieve lock on entity: " + entity + ". Reason: " + e, e); } return false; } }
From source file:org.eclipse.emf.teneo.hibernate.resource.HbResourceImpl.java
License:Open Source License
/** * Creates the session of this resource. As a default the FlushMode is set * to Never. The loaded objects of this resource are merged into the * session. It is the responsibility of the caller to close the session or * call the returnSession method here./*from w ww. jav a 2 s .c o m*/ */ public Session getSession() { if (log.isDebugEnabled()) { log.debug("Creating session"); } final SessionFactory sessionFactory = emfDataStore.getSessionFactory(); final Session session = sessionFactory.openSession(); session.setFlushMode(FlushMode.MANUAL); if (loadedEObjects.size() > 0) { session.beginTransaction(); // merge the loaded objects into the session if (log.isDebugEnabled()) { log.debug("Merging " + loadedEObjects.size() + " eobjects into new session "); } for (Object obj : loadedEObjects) { session.buildLockRequest(LockOptions.NONE).lock(obj); } session.getTransaction().commit(); } return session; }
From source file:org.grails.orm.hibernate.GrailsHibernateTemplate.java
License:Apache License
public void lock(final Object entity, final LockMode lockMode) throws DataAccessException { doExecute(new HibernateCallback<Object>() { public Object doInHibernate(Session session) throws HibernateException { session.buildLockRequest(new LockOptions(lockMode)).lock(entity);//LockMode.PESSIMISTIC_WRITE return null; }// ww w . j av a 2 s. co m }, true); }