Example usage for org.hibernate ReplicationMode IGNORE

List of usage examples for org.hibernate ReplicationMode IGNORE

Introduction

In this page you can find the example usage for org.hibernate ReplicationMode IGNORE.

Prototype

ReplicationMode IGNORE

To view the source code for org.hibernate ReplicationMode IGNORE.

Click Source Link

Document

Ignore replicated entities when a row already exists.

Usage

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/*from w ww .j  a va2s  .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.
 * //from www. j  ava2  s  .  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
 * 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.
 * /* ww  w. j a  v a 2 s. 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.bedework.calcore.hibernate.HibSessionImpl.java

License:Apache License

/** Save a new object with the given id. This should only be used for
 * restoring the db from a save./*from  w  ww. jav a2 s.  c om*/
 *
 * @param obj
 * @throws CalFacadeException
 */
@Override
public void restore(final Object obj) throws CalFacadeException {
    if (exc != null) {
        // Didn't hear me last time?
        throw new CalFacadeException(exc);
    }

    try {
        sess.replicate(obj, ReplicationMode.IGNORE);
    } catch (Throwable t) {
        handleException(t);
    }
}

From source file:org.bedework.carddav.server.dirHandlers.db.HibSessionImpl.java

License:Apache License

/** Save a new object with the given id. This should only be used for
 * restoring the db from a save./*from   w ww  . ja va  2s . c o  m*/
 *
 * @param obj
 * @throws WebdavException
 */
public void restore(final Object obj) throws WebdavException {
    if (exc != null) {
        // Didn't hear me last time?
        throw new WebdavException(exc);
    }

    try {
        sess.replicate(obj, ReplicationMode.IGNORE);
    } catch (Throwable t) {
        handleException(t);
    }
}

From source file:org.bedework.dumprestore.HibSession.java

License:Apache License

/** Save a new object with the given id. This should only be used for
 * restoring the db from a save.//  w  ww.ja  v a  2s .  co  m
 *
 * @param obj
 * @throws CalFacadeException
 */
public void restore(Object obj) throws CalFacadeException {
    if (exc != null) {
        // Didn't hear me last time?
        throw new CalFacadeException(exc);
    }

    try {
        sess.replicate(obj, ReplicationMode.IGNORE);
    } catch (Throwable t) {
        handleException(t);
    }
}

From source file:org.bedework.util.hibernate.HibSessionImpl.java

License:Apache License

/** Save a new object with the given id. This should only be used for
 * restoring the db from a save./*  w  w w  . j  a  v  a 2 s  .  c  o  m*/
 *
 * @param obj
 * @throws HibException
 */
@Override
public void restore(final Object obj) throws HibException {
    if (exc != null) {
        // Didn't hear me last time?
        throw new HibException(exc);
    }

    try {
        sess.replicate(obj, ReplicationMode.IGNORE);
    } catch (Throwable t) {
        handleException(t);
    }
}

From source file:ro.cs.om.model.dao.impl.DaoRoleImpl.java

License:Open Source License

/**
 * same thing as addDefaultRoles(Integer organisationId, Integer moduleId) but using the same session
 *//*  ww w  .jav  a2 s  .  c o m*/
public void addDefaultRoles(Integer organisationId, Integer moduleId, Session session) {
    logger.debug("Add default roles DAO IMPL - START- ");
    List<RoleWeb> roles = getDefaultRolesByModule(moduleId);
    for (RoleWeb role : roles) {
        role.setOrganisationId(organisationId);
        role.setModuleId(moduleId);
        Localization description = new Localization();
        description.setLocalizationId(0);
        description.setEn(role.getDescription().getEn());
        description.setRo(role.getDescription().getRo());
        logger.debug("description role = " + role.getDescription());
        session.save(IModelConstant.localizationEntity, description);
        role.setDescription(description);
        //session.evict(IModelConstant.roleWebEntity);
        //logger.debug("After evict " + role);
        role.setRoleId(0);
        logger.debug("Role " + role);
        session.replicate(IModelConstant.roleWebEntity, role, ReplicationMode.IGNORE);
        logger.debug("fter save " + role);
    }
    logger.debug("Add default roles DAO IMPL - END- ");
}