Example usage for org.hibernate Session replicate

List of usage examples for org.hibernate Session replicate

Introduction

In this page you can find the example usage for org.hibernate Session replicate.

Prototype

void replicate(Object object, ReplicationMode replicationMode);

Source Link

Document

Persist the state of the given detached instance, reusing the current identifier value.

Usage

From source file:com.axway.academy.addressbook.core.AccountManagerImpl.java

License:Open Source License

/**
 * Persist a new account and a user associated with the account.
 *
 * @param account the new {@code Account} object that holds the account's attributes.
 * @param user the new {@code User} object that holds the user's attributes to be created along with the account.
 *            May be set to {@code null} to create an account without a user.
 * @return An array of the newly persisted {@code Account} and {@code User} objects.
 * @throws DuplicateAccountException if the specified account already exists.
 * @throws DuplicateUserException if the specified user already exists.
 * @throws PasswordPolicyException if the passphrase set for the user does not fulfill the password policy
 *             requirements.//from  w w w . java2  s.  c  o m
 * @throws AccountConstraintException if the account home folder is not valid.
 */
private Account persistAccount(Account account)
        throws DuplicateAccountException, PasswordPolicyException, AccountConstraintException {

    if (account.getId() != null) {
        throw new IllegalArgumentException("Instantiated from Template");
    }

    Session session = mSessionFactoryManager.getSessionFactory().openSession();

    try {

        ConstraintValidationUtil.validateNewAccount(session, (AccountBean) account);

        Transaction tx = session.beginTransaction();

        Account persistedAccount = account;
        try {
            if (account.getId() == null) {
                // If object does not have an id, persist a copy so if exception is thrown original object is
                // unchanged.
                persistedAccount = ((AccountBean) account).copy();
                session.save(persistedAccount);
            } else {
                session.replicate(persistedAccount, ReplicationMode.OVERWRITE);
            }
        } catch (ConstraintViolationException ex) {
            // Assume this is a uniqueness violation on the name since that is the only constraint in this bean.
            throw new DuplicateAccountExceptionImpl(account, "Duplicate account: " + account.getLoginname(),
                    ex);
        } catch (HibernateException e) {
            final String message = "Database error creating account";
            throw new RuntimeException(message, e);
        }
        session.flush();

        tx.commit();

        if (sLogger.isDebugEnabled()) {
            sLogger.debug("76568:createAccount : " + account);
        }

        return persistedAccount;
    } finally {
        SessionManagerFactory.closeSession(session);
    }
}

From source file:com.axway.academy.addressbook.core.AccountManagerImpl.java

License:Open Source License

@Override
public void updateAccount(Account account) throws NoSuchAccountException, DuplicateAccountException,
        PasswordPolicyException, AccountConstraintException {

    Session session = mSessionFactoryManager.getSessionFactory().openSession();

    try {/*from ww  w . j av a2s.  c  o m*/

        ConstraintValidationUtil.validateUpdateAccount(session, (AccountBean) account);

        Transaction tx = session.beginTransaction();

        try {
            session.replicate(account, ReplicationMode.OVERWRITE);
            session.flush();

        } catch (UnresolvableObjectException ex) {
            throw new NoSuchAccountException(account.getLoginname(), ex);
        } catch (ConstraintViolationException ex) {
            throw new DuplicateAccountExceptionImpl(account, "Duplicate account: " + account.getLoginname(),
                    ex);
        }

        tx.commit();

        if (sLogger.isDebugEnabled()) {
            sLogger.debug("76568: updateAccount updated: " + account, new Throwable("trace caller"));
        }

    } finally {
        SessionManagerFactory.closeSession(session);
    }

}

From source file:com.jdon.persistence.hibernate.HibernateTemplate.java

License:Apache License

public void replicate(final Object entity, final ReplicationMode replicationMode) throws Exception {

    doHibernate(new HibernateCallback() {
        public Object execute(Session session) throws HibernateException {
            session.replicate(entity, replicationMode);
            return null;
        }//  ww w .  ja v a  2s.c o  m
    });
}

From source file:de.codesourcery.eve.skills.util.DBConverter.java

License:Apache License

protected void export(Class<?> entity) {

    System.out.println("\n============\nExporting " + entity.getName() + "\n============");

    // load data// w  w w  . ja  v  a  2  s.  co m
    System.out.print("Opening MySQL session ...");
    final Session mysqlSession = mysql.openSession();
    System.out.print("created.");

    //      mysqlSession.setFlushMode( FlushMode.MANUAL );

    Transaction mysqlTransaction = mysqlSession.beginTransaction();

    final Criteria criteria = mysqlSession.createCriteria(entity);

    // replicate data
    System.out.print("Opening HSQL session ...");
    final Session hsqlSession = hsql.openSession();
    System.out.println("created.");
    //      mysqlSession.setFlushMode( FlushMode.MANUAL );

    final Transaction hsqlTransaction = hsqlSession.beginTransaction();

    final ScrollableResults data = criteria.scroll();
    int count = 0;
    int dotCount = 0;
    try {
        while (data.next()) {
            Object loaded = data.get(0);
            //            if ( entity == MarketGroup.class ) {
            //               MarketGroup group = (MarketGroup) loaded;
            //               System.out.println( group.getId() +" -> "+group.getParent() );
            //            }
            hsqlSession.replicate(loaded, ReplicationMode.IGNORE);
            if ((++count % 1000) == 0) { // make sure to adjust <prop key="hibernate.jdbc.batch_size">1000</prop> in config !!
                hsqlSession.flush();
                hsqlSession.clear();
                mysqlSession.flush();
                mysqlSession.clear();
                System.out.print(".");
                dotCount++;
                if (dotCount == 60) {
                    System.out.println();
                    dotCount = 0;
                }
            }
        }
    } finally {
        data.close();
        System.out.println("\nExported " + count + " entries");
    }

    if (mysqlTransaction.isActive()) {
        mysqlTransaction.commit();
    }

    if (hsqlTransaction.isActive()) {
        hsqlTransaction.commit();
    }

    hsqlSession.flush();
    mysqlSession.flush();

    mysqlSession.close();
    hsqlSession.close();
}

From source file:gr.interamerican.bo2.impl.open.hibernate.TestScenarioInvoiceHibernateOperations.java

License:Open Source License

/**
 * THIS TEST IS FOR EXPERIMENTAL USE ONLY. IT IS NOT CERTAIN THAT IT WILL PASS.
 * //  w  ww.  j  a  v a 2s  . c  om
 * Tests re-attaching a detached MODIFIED instance, re-attaching it SOMEHOW,
 * modifying again, checking that lazy proxies can be initialized and finally
 * flushing the session.
 * 
 * The expected outcome is that the changes are not persisted.
 * 
 * <li>transaction1: store
 * <li>transaction2: read
 * <li>transaction3: modify, re-attach, modify and flush
 * <li>transaction4: confirm operations
 * 
 * @throws UnexpectedException
 * @throws DataException
 * @throws LogicException
 */
//@Test
public void testReattach_Modified_Flush() 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);

    /* add a new line with a subLine */
    InvoiceLine newLine = factory.sampleInvoiceLine(5);
    newLine.getSubLines().add(factory.sampleInvoiceSubLine(newLine.getLineNo()));
    invoice.getLines().add(newLine);

    AbstractPersistenceOperation<Invoice> updateOp = new AbstractPersistenceOperation<Invoice>(Invoice.class) {
        @Override
        public void execute() throws LogicException, DataException {
            /* 
             * re-attach with session.replicate(invoice, ReplicationMode.IGNORE)
             */
            try {
                Session session = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$
                        .getHibernateSession();
                /* DO MAGIC HERE */
                session.replicate(invoice, ReplicationMode.IGNORE); //this doesn't work
                //session.buildLockRequest(LockOptions.NONE).lock(invoice); //this doesn't work
                /* END DO MAGIC */
                assertTrue(invoice.getLines().size() == 5);
                /* add another line */
                InvoiceLine newLine2 = factory.sampleInvoiceLine(6);
                newLine2.getSubLines().add(factory.sampleInvoiceSubLine(newLine2.getLineNo()));
                invoice.getLines().add(newLine2);
                assertTrue(invoice.getLines().size() == 6);
                /* finally, add a subLine to each line. */
                Set<InvoiceLine> lines = invoice.getLines();
                for (InvoiceLine line : lines) {
                    assertNotNull(line.getSubLines());
                    line.getSubLines().size(); //make sure we can initialize lazy proxies.
                    line.getSubLines().add(factory.sampleInvoiceSubLine(line.getLineNo() + 1));
                }
                invoice.tidy();
                /* 
                 * The invoice now has 6 lines, each one of which has 2 subLines.
                 * We flush (after fixing keys). We will confirm later on that
                 * the changes were not persisted on flush, i.e. that the persisted
                 * invoice has 4 lines, each one of which has 1 subLine.
                 */
                session.flush();
            } catch (InitializationException e) {
                fail(e.toString());
            }
        }
    };
    updateOp.setPo(invoice);
    Execute.transactional(updateOp);

    /* confirm results, only 4 lines in DB. Each one has 1 subLine */
    AbstractPersistenceOperation<Invoice> readOp2 = new AbstractPersistenceOperation<Invoice>(Invoice.class) {
        @Override
        public void execute() throws LogicException, DataException {
            invoice = pw.read(po);
            Set<InvoiceLine> lines = invoice.getLines();
            assertTrue(lines.size() == 4);
            for (InvoiceLine line : lines) {
                assertTrue(line.getSubLines().size() == 1);
            }
        }
    };
    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

/**
 * THIS TEST IS FOR EXPERIMENTAL USE ONLY. IT IS NOT CERTAIN THAT IT WILL PASS.
 * /*w  ww  .  ja  va 2s  .  c o  m*/
 * Tests re-attaching a detached MODIFIED instance, re-attaching it SOMEHOW,
 * modifying again, checking that lazy proxies can be initialized and finally
 * updating it with a {@link GenericHibernatePersistenceWorker}.
 * 
 * The expected outcome is that the changes are persisted. The difference
 * with the previous case, is that the worker will call session.merge() and 
 * then flush.
 * 
 * <li>transaction1: store
 * <li>transaction2: read
 * <li>transaction3: modify, re-attach, modify and update with worker
 * <li>transaction4: confirm operations
 * 
 * @throws UnexpectedException
 * @throws DataException
 * @throws LogicException
 */
//@Test
public void testReattach_Modified_WorkerUpdate() 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);

    /* add a new line with a subLine */
    InvoiceLine newLine = factory.sampleInvoiceLine(5);
    newLine.getSubLines().add(factory.sampleInvoiceSubLine(newLine.getLineNo()));
    invoice.getLines().add(newLine);

    AbstractPersistenceOperation<Invoice> updateOp = new AbstractPersistenceOperation<Invoice>(Invoice.class) {
        @Override
        public void execute() throws LogicException, DataException {
            /* 
             * re-attach with session.update()
             * merge() has the same effect, but we call merge in worker.update() anyway.
             */
            try {
                Session session = getProvider().getResource("LOCALDB", HibernateSessionProvider.class) //$NON-NLS-1$
                        .getHibernateSession();
                /* DO MAGIC HERE */
                session.replicate(invoice, ReplicationMode.IGNORE); //this doesn't work
                //session.buildLockRequest(LockOptions.NONE).lock(invoice); //this doesn't work
                /* END DO MAGIC */
                assertTrue(invoice.getLines().size() == 5);
                /* add another line */
                InvoiceLine newLine2 = factory.sampleInvoiceLine(6);
                newLine2.getSubLines().add(factory.sampleInvoiceSubLine(newLine2.getLineNo()));
                invoice.getLines().add(newLine2);
                assertTrue(invoice.getLines().size() == 6);
                /* finally, add a subLine to each line. */
                Set<InvoiceLine> lines = invoice.getLines();
                for (InvoiceLine line : lines) {
                    assertNotNull(line.getSubLines());
                    line.getSubLines().add(factory.sampleInvoiceSubLine(line.getLineNo() + 1));
                }

                /* 
                 * The invoice now has 6 lines, each one of which has 2 subLines.
                 * We perform an update with a worker. We will confirm later on that
                 * the changes were persisted on update, i.e. that the persisted
                 * invoice has 6 lines, each one of which has 2 subLines.
                 */
                pw.update(invoice);
            } catch (InitializationException e) {
                fail(e.toString());
            }
        }
    };
    updateOp.setPo(invoice);
    Execute.transactional(updateOp);

    /* confirm results, 6 lines. Each one has 2 subLine */
    AbstractPersistenceOperation<Invoice> readOp2 = new AbstractPersistenceOperation<Invoice>(Invoice.class) {
        @Override
        public void execute() throws LogicException, DataException {
            invoice = pw.read(po);
            Set<InvoiceLine> lines = invoice.getLines();
            assertTrue(lines.size() == 6);
            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:org.opengoss.dao.hibernate.DataAccessor.java

License:Apache License

public void replicate(final Object entity, final ReplicationMode replicationMode) throws DaoException {

    execute(new IAccessorCallback() {
        public Object call(Session session) throws HibernateException {
            session.replicate(entity, replicationMode);
            return null;
        }//ww w.  j a va 2  s . c om
    });
}

From source file:org.springframework.orm.hibernate3.HibernateTemplate.java

License:Apache License

@Override
public void replicate(final Object entity, final ReplicationMode replicationMode) throws DataAccessException {

    executeWithNativeSession(new HibernateCallback<Object>() {
        @Override//from  w  w  w .  j  av  a  2 s  . c  o m
        public Object doInHibernate(Session session) throws HibernateException {
            checkWriteOperationAllowed(session);
            session.replicate(entity, replicationMode);
            return null;
        }
    });
}

From source file:org.springframework.orm.hibernate3.StatelessHibernateTemplate.java

License:Apache License

public void replicate(final Object entity, final ReplicationMode replicationMode) throws DataAccessException {

    execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            checkWriteOperationAllowed(session);
            session.replicate(entity, replicationMode);
            return null;
        }/*from   w  w  w  . java2s.  c o m*/
    }, true);
}