Example usage for org.hibernate Session merge

List of usage examples for org.hibernate Session merge

Introduction

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

Prototype

Object merge(Object object);

Source Link

Document

Copy the state of the given object onto the persistent object with the same identifier.

Usage

From source file:com.chingo247.structureapi.persistence.service.ValidationService.java

License:Open Source License

private void removeCreatedBefore(String world, Timestamp timestamp) {
    Session session = null;
    Transaction tx = null;// ww  w .j av a 2  s  . c  o  m
    try {
        session = HibernateUtil.getSession();
        tx = session.beginTransaction();
        QStructure qct = QStructure.structure;
        JPQLQuery query = new HibernateQuery(session);
        List<Structure> structures = query.from(qct).where(qct.logEntry().createdAt.after(timestamp)
                .and(qct.location().world.eq(world)).and(qct.state.ne(State.REMOVED))).list(qct);
        if (!structures.isEmpty()) {
            StructureAPI.print("World '" + world + "' has " + structures.size()
                    + " structures that were placed after the last world save");
        }
        Iterator<Structure> it = structures.iterator();
        World w = Bukkit.getWorld(world);
        if (w == null)
            return;

        RegionManager rmgr = WorldGuardUtil.getRegionManager(w);
        if (rmgr == null)
            return;

        Date removeDate = new Date();
        while (it.hasNext()) {
            Structure structure = it.next();
            rmgr.removeRegion(structure.getStructureRegion());
            StructureAPI.print("Region: " + structure.getStructureRegion() + " has been removed");
            structure.setState(State.REMOVED);
            structure.getLog().setRemovedAt(new Timestamp(removeDate.getTime()));
            structure.getLog().setAutoremoved(true);
            session.merge(structure);
        }

        try {
            rmgr.save();
            tx.commit();
        } catch (StorageException ex) {
            Logger.getLogger(ValidationService.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (HibernateException e) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (HibernateException rbe) {
            java.util.logging.Logger.getLogger(AbstractService.class.getName()).log(Level.SEVERE,
                    "Couldnt roll back transaction", rbe);
        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:com.chingo247.structureapi.plan.schematic.SchematicManager.java

License:Open Source License

private void save(final List<File> schematics) {

    final List<SchematicData> data = new LinkedList<>();
    List<Future> tasks = new LinkedList<>();

    for (final File file : schematics) {
        tasks.add(executor.submit(new Runnable() {

            @Override//  w  w  w .j  ava  2  s .  co m
            public void run() {
                try {
                    data.add(SchematicData.load(file));
                } catch (IOException | DataException ex) {
                    Logger.getLogger(SchematicManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }));
    }

    for (Future task : tasks) {
        try {
            task.get();
        } catch (InterruptedException | ExecutionException ex) {
            Logger.getLogger(SchematicManager.class.getName()).log(Level.SEVERE, null, ex);
            for (Future f : tasks) {
                f.cancel(true);
            }
        }
    }

    Session session = null;
    Transaction tx = null;
    try {
        session = HibernateUtil.getSession();
        tx = session.beginTransaction();
        for (SchematicData schematicData : data) {
            session.merge(schematicData);
        }
        tx.commit();
    } catch (HibernateException e) {
        try {
            tx.rollback();
        } catch (HibernateException rbe) {
            Logger.getLogger(AbstractService.class.getName()).log(Level.SEVERE,
                    "Couldnt roll back transaction", rbe);
        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:com.corvid.json.hibernate.test.HibernateCustomTypeTest.java

License:Apache License

@SuppressWarnings("unchecked")
private <E> E save(E entity) {
    Session session = sessionFactory.openSession();
    session.beginTransaction();//from  ww  w . j  a v a2 s  . c o m
    Object entityAttached = session.merge(entity);
    session.getTransaction().commit();

    return (E) entityAttached;
}

From source file:com.daro.persistence.generic.dao.GenericDaoImpl.java

License:GNU General Public License

/**
 * Update entity p. Persists existing entity p.
 * /*from  w w  w . j  a v  a  2 s. com*/
 * @param p T Data type of entity
 * @throws PersistenceException
 */
@Override
public void update(T p) throws PersistenceException {
    Session session = this.getCurrentSession();

    try {
        //session.update(p);
        session.merge(p);
    } catch (java.lang.IllegalArgumentException illegalArgumentEx) {
        logger.error("Persistence layer error: " + illegalArgumentEx.getStackTrace());
        PersistenceError error;
        if (p == null) {
            error = PersistenceError.ENTITY_NULL;
        } else {
            error = PersistenceError.PERSISTENCE_INTERNAL_ERROR;
        }
        throw new PersistenceException(error, illegalArgumentEx.getCause());
    }

    if (loggerInfoEnabled)
        logger.debug("Persistence layer info: " + "Person updated successfully, Person Details=" + p);
}

From source file:com.dell.asm.asmcore.asmmanager.db.FirmwareRepositoryDAO.java

License:Open Source License

public FirmwareRepositoryEntity saveOrUpdate(final FirmwareRepositoryEntity entity) {
    Session session = null;
    Transaction tx = null;//from   ww w .  j  av  a  2  s .c om

    try {
        session = dao.getNewSession();
        tx = session.beginTransaction();
        final String user = dao.extractUserFromRequest();
        final Date now = new Date();
        final FirmwareRepositoryEntity persisted = (FirmwareRepositoryEntity) session
                .get(FirmwareRepositoryEntity.class, entity.getId());
        if (persisted == null) {
            entity.setCreatedDate(now);
            entity.setCreatedBy(user);
            entity.setUpdatedDate(now);
            entity.setUpdatedBy(user);
            session.save(entity);
        } else {
            entity.setUpdatedDate(now);
            entity.setUpdatedBy(user);
            session.merge(entity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.warn("Caught exception during createFirmwareRepository: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during createFirmwareRepository: " + ex);
        }
        throw new AsmManagerInternalErrorException("createFirmwareRepository", "FirmwareRepositoryDAO", e);
    } finally {
        dao.cleanupSession(session, "createFirmwareRepository");
    }

    return entity;
}

From source file:com.dell.asm.asmcore.asmmanager.db.FirmwareRepositoryDAO.java

License:Open Source License

public FirmwareRepositoryEntity merge(final FirmwareRepositoryEntity original,
        final FirmwareRepositoryEntity update) {
    Session session = null;
    Transaction tx = null;//  w w  w  .j a  va2  s . c o m

    try {
        session = dao.getNewSession();
        tx = session.beginTransaction();

        if (original != null) {
            final String originalId = original.getId();
            session.load(original, originalId);
            original.getDeployments().clear();
            original.getSoftwareBundles().clear();
            original.getSoftwareComponents().clear();
            original.getTemplates().clear();
            original.getDeviceInventoryComplianceEntities().clear();
            session.flush();
            // reload the original entity in cache so we can merge
            session.get(FirmwareRepositoryEntity.class, originalId);
            update.setId(originalId);
            update.setCreatedDate(original.getCreatedDate());
            update.setCreatedBy(original.getCreatedBy());
            update.setUpdatedDate(new Date());
            update.setUpdatedBy(dao.extractUserFromRequest());
            session.merge(update);
        } else {
            update.setCreatedDate(new Date());
            update.setCreatedBy(dao.extractUserFromRequest());
            update.setUpdatedDate(update.getCreatedDate());
            update.setUpdatedBy(update.getCreatedBy());
            session.saveOrUpdate(update);
        }

        // Commit transaction.
        tx.commit();
    } catch (Exception e) {
        logger.warn("Caught exception during merge: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during merge: " + ex);
        }
        throw new AsmManagerInternalErrorException("merge", "FirmwareRepositoryDAO", e);
    } finally {
        dao.cleanupSession(session, "merge");
    }

    return original;
}

From source file:com.dgc.DAO.GenericDao.java

public E merge(E entity) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();//ww w . j a va  2s  .  co m
    session.merge(entity);
    session.getTransaction().commit();
    return entity;
}

From source file:com.eby.orm.dao.GenericDAO.java

public void delete(final Object object) {
    Session session = sessionFactory.getCurrentSession();
    try {//from   w  ww. j a  v a2s.  co m
        session.getTransaction().begin();
        Object object1 = session.merge(object);
        session.delete(object1);
        session.getTransaction().commit();
    } catch (Exception e) {
        session.getTransaction().rollback();
    }

}

From source file:com.eby.orm.dao.GenericDAO.java

/**
 *
 *//*from   w ww  .j  a  v  a  2  s . c o  m*/
public void update(final Object o) {
    Session session = sessionFactory.getCurrentSession();
    try {
        session.getTransaction().begin();
        Object object1 = session.merge(o);
        session.update(object1);
        session.getTransaction().commit();
    } catch (Exception e) {
        session.getTransaction().rollback();
    }
}

From source file:com.eby.orm.dao.GenericDAO.java

/**
 *
 *//*from   www.  j ava2s .c o  m*/
public void saveOrUpdate(final Object o) {
    Session session = sessionFactory.getCurrentSession();
    try {
        session.getTransaction().begin();
        Object object1 = session.merge(o);
        session.saveOrUpdate(object1);
        session.getTransaction().commit();
    } catch (Exception e) {
        session.getTransaction().rollback();
    }
}