Example usage for org.hibernate Session saveOrUpdate

List of usage examples for org.hibernate Session saveOrUpdate

Introduction

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

Prototype

void saveOrUpdate(Object object);

Source Link

Document

Either #save(Object) or #update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking).

Usage

From source file:com.almuradev.backpack.backend.DatabaseManager.java

License:MIT License

public static void saveSlot(Session session, Backpacks backpack, int slotIndex, DataContainer slotData)
        throws IOException, SQLException {
    Slots slotsRecord = (Slots) session.createCriteria(Slots.class)
            .add(Restrictions.and(Restrictions.eq("backpacks", backpack), Restrictions.eq("slot", slotIndex)))
            .uniqueResult();//w  ww . j a  v a 2  s  . c om

    if (slotData == null && slotsRecord != null) {
        session.delete(slotsRecord);
    } else if (slotData != null && slotsRecord != null) {
        final StringWriter writer = new StringWriter();
        HoconConfigurationLoader loader = HoconConfigurationLoader.builder()
                .setSink(() -> new BufferedWriter(writer)).build();
        loader.save(ConfigurateTranslator.instance().translateData(slotData));
        slotsRecord.setData(new SerialClob(writer.toString().toCharArray()));
        session.saveOrUpdate(slotsRecord);
    } else if (slotData != null) {
        slotsRecord = new Slots();
        slotsRecord.setBackpacks(backpack);
        slotsRecord.setSlot(slotIndex);
        final StringWriter writer = new StringWriter();
        HoconConfigurationLoader loader = HoconConfigurationLoader.builder()
                .setSink(() -> new BufferedWriter(writer)).build();
        loader.save(ConfigurateTranslator.instance().translateData(slotData));
        slotsRecord.setData(new SerialClob(writer.toString().toCharArray()));
        session.saveOrUpdate(slotsRecord);
    }
}

From source file:com.almuradev.backpack.backend.DatabaseManager.java

License:MIT License

private static boolean change(Session session, BackpackInventory inventory, boolean upgrade, CommandSource src,
        Player player) {/*from   w  ww.ja  va  2 s .  c om*/
    final int originalSize = inventory.getRecord().getSize();
    final int targetSize = originalSize + (upgrade ? 9 : -9);
    if (targetSize < 9 || targetSize > 54) {
        session.close();
        final String node = "template.backpack.change.limit";
        final TextTemplate template = Backpack.instance.storage.getChildNodeValue(node, TextTemplate.class);
        src.sendMessage(template,
                ImmutableMap.of("target",
                        src == player ? Text.of("Your")
                                : Text.of(TextColors.LIGHT_PURPLE, player.getName(), TextColors.RESET, "'s"),
                        "change", Text.of(upgrade ? "maximum" : "minimum")));
        return false;
    }
    final Backpacks record = (Backpacks) session.createCriteria(Backpacks.class)
            .add(Restrictions.eq("backpackId", inventory.getRecord().getBackpackId())).uniqueResult();
    if (record != null) {
        record.setSize(targetSize);
        session.beginTransaction();
        session.saveOrUpdate(record);
        session.getTransaction().commit();

        final BackpackInventory changed = new BackpackInventory(record);
        for (int i = 0; i < record.getSize(); i++) {
            changed.setInventorySlotContents(i, inventory.getStackInSlot(i));
        }

        BackpackFactory.put(changed);
        session.close();
        if (src != player) {
            src.sendMessage(
                    Backpack.instance.storage.getChildNodeValue("template.backpack.change.success",
                            TextTemplate.class),
                    ImmutableMap.of("target",
                            Text.of(TextColors.LIGHT_PURPLE, player.getName(), TextColors.RESET, "'s"),
                            "change",
                            upgrade ? Text.of(TextColors.GREEN, "upgraded")
                                    : Text.of(TextColors.RED, "downgraded"),
                            "originalSize", Text.of(originalSize), "targetSize", Text.of(targetSize)));
        }
        player.sendMessage(
                Backpack.instance.storage.getChildNodeValue("template.backpack.change.success",
                        TextTemplate.class),
                ImmutableMap.of("target", Text.of("Your"), "change",
                        upgrade ? Text.of(TextColors.GREEN, "upgraded") : Text.of(TextColors.RED, "downgraded"),
                        "originalSize", Text.of(originalSize), "targetSize", Text.of(targetSize)));
        return true;
    }
    session.close();
    src.sendMessage(
            Backpack.instance.storage.getChildNodeValue("template.backpack.change.failure", TextTemplate.class),
            ImmutableMap.of("change",
                    upgrade ? Text.of(TextColors.GREEN, "upgrade") : Text.of(TextColors.RED, "downgrade"),
                    "target", src == player ? Text.of("Your")
                            : Text.of(TextColors.LIGHT_PURPLE, player.getName(), TextColors.RESET, "'s")));
    return false;
}

From source file:com.almuradev.backpack.BackpackFactory.java

License:MIT License

public static BackpackInventory load(World world, Player player) throws IOException, SQLException {
    final Session session = DatabaseManager.getSessionFactory().openSession();
    final Criteria criteria = session.createCriteria(Backpacks.class);
    Backpacks record = (Backpacks) criteria
            .add(Restrictions.and(Restrictions.eq("worldUniqueId", world.getUniqueId()),
                    Restrictions.eq("playerUniqueId", player.getUniqueId())))
            .uniqueResult();/*from ww w  . j  a  va2  s.c om*/

    if (record == null) {
        record = new Backpacks();
        record.setWorldUniqueId(world.getUniqueId());
        record.setPlayerUniqueId(player.getUniqueId());
        record.setSize(9);
        record.setTitle("My Backpack");
        session.beginTransaction();
        session.saveOrUpdate(record);
        session.getTransaction().commit();
    }
    final BackpackInventory inventory = new BackpackInventory(record);
    for (int i = 0; i < inventory.getSizeInventory(); i++) {
        DatabaseManager.loadSlot(session, inventory, i);
    }
    session.close();
    BACKPACKS.add(inventory);
    return new BackpackInventory(record);
}

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

@Override
public void update(Iterable<DataRecord> records) {
    assertPrepared();//from  w w  w. j a va 2  s . c o  m
    Session session = this.getCurrentSession();
    try {
        storageClassLoader.bind(Thread.currentThread());
        DataRecordConverter<Object> converter = new ObjectDataRecordConverter(storageClassLoader, session);
        for (DataRecord currentDataRecord : records) {
            TypeMapping mapping = mappingRepository.getMappingFromUser(currentDataRecord.getType());
            Wrapper o = (Wrapper) converter.convert(currentDataRecord, mapping);
            if (session.contains(o) && session.isReadOnly(o)) { // A read only instance for an update?
                // Session#setReadOnly(...) does not always work as expected (especially in case of compound keys
                // see TMDM-7014).
                session.evict(o);
                o = (Wrapper) converter.convert(currentDataRecord, mapping);
            }
            DataRecordMetadata recordMetadata = currentDataRecord.getRecordMetadata();
            Map<String, String> recordProperties = recordMetadata.getRecordProperties();
            if (!ObjectUtils.equals(recordMetadata.getTaskId(), o.taskId())) {
                o.taskId(recordMetadata.getTaskId());
            }
            for (Map.Entry<String, String> currentProperty : recordProperties.entrySet()) {
                String key = currentProperty.getKey();
                String value = currentProperty.getValue();
                ComplexTypeMetadata database = mapping.getDatabase();
                if (database.hasField(key)) {
                    Object convertedValue = StorageMetadataUtils.convert(value, database.getField(key));
                    if (!ObjectUtils.equals(convertedValue, o.get(key))) {
                        o.set(key, convertedValue);
                    }
                } else {
                    throw new IllegalArgumentException("Can not store value '" + key //$NON-NLS-1$
                            + "' because there is no database field '" + key + "' in type '" + mapping.getName() //$NON-NLS-1$ //$NON-NLS-2$
                            + "' (storage is '" + toString() + "')"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            session.saveOrUpdate(o);
            if (FLUSH_ON_LOAD && session.getStatistics().getEntityCount() % batchSize == 0) {
                // Periodically flush objects to avoid using too much memory.
                session.flush();
            }
        }
    } catch (ConstraintViolationException e) {
        throw new com.amalto.core.storage.exception.ConstraintViolationException(e);
    } catch (PropertyValueException e) {
        throw new RuntimeException("Invalid value in record to update.", e); //$NON-NLS-1$
    } catch (NonUniqueObjectException e) {
        throw new RuntimeException("Attempted to update multiple times same record within same transaction.", //$NON-NLS-1$
                e);
    } catch (Exception e) {
        throw new RuntimeException("Exception occurred during update.", e); //$NON-NLS-1$
    } finally {
        this.releaseSession();
        storageClassLoader.unbind(Thread.currentThread());
    }
}

From source file:com.anite.zebra.hivemind.taskAction.FireAndForgetSubprocess.java

License:Apache License

public void runTask(ITaskInstance taskInstance) throws RunTaskException {
    String processName = null;//from w ww  . j  av a2  s  . co  m

    Zebra zebra = RegistryHelper.getInstance().getZebra();

    try {
        ZebraTaskInstance antelopeTaskInstance = (ZebraTaskInstance) taskInstance;
        processName = ((ZebraTaskDefinition) taskInstance.getTaskDefinition()).getSubProcessName();

        ZebraProcessInstance subProcessInstance = zebra.createProcessPaused(processName);

        Session s = RegistryHelper.getInstance().getSession();
        Transaction t = s.beginTransaction();

        subProcessInstance.setParentTaskInstance(antelopeTaskInstance);
        subProcessInstance
                .setParentProcessInstance((ZebraProcessInstance) antelopeTaskInstance.getProcessInstance());

        // Map related class needed for security passing
        subProcessInstance.setRelatedClass(antelopeTaskInstance.getZebraProcessInstance().getRelatedClass());
        subProcessInstance.setRelatedKey(antelopeTaskInstance.getZebraProcessInstance().getRelatedKey());

        // map any inputs into the process
        mapTaskInputs((ZebraProcessInstance) antelopeTaskInstance.getProcessInstance(), subProcessInstance);

        // Now NULL parent taskinstace
        subProcessInstance.setParentTaskInstance(null);

        s.saveOrUpdate(subProcessInstance);
        taskInstance.setState(ITaskInstance.STATE_AWAITINGCOMPLETE);
        s.saveOrUpdate(taskInstance);
        t.commit();

        // kick off the process
        zebra.startProcess(subProcessInstance);
    } catch (Exception e) {
        String emsg = "runTask failed to create Process " + processName;
        log.error(emsg, e);
        throw new RunTaskException(emsg, e);
    }

}

From source file:com.anite.zebra.hivemind.taskAction.SubProcess.java

License:Apache License

public void runTask(ITaskInstance taskInstance) throws RunTaskException {
    String processName = null;/*from www  .  j a va 2 s.  c o m*/

    Zebra zebra = RegistryHelper.getInstance().getZebra();

    try {
        ZebraTaskInstance antelopeTaskInstance = (ZebraTaskInstance) taskInstance;
        processName = ((ZebraTaskDefinition) taskInstance.getTaskDefinition()).getSubProcessName();

        ZebraProcessInstance subProcessInstance = zebra.createProcessPaused(processName);

        Session s = RegistryHelper.getInstance().getSession();
        Transaction t = s.beginTransaction();

        subProcessInstance.setParentTaskInstance(antelopeTaskInstance);
        subProcessInstance
                .setParentProcessInstance((ZebraProcessInstance) antelopeTaskInstance.getProcessInstance());

        // Map related class needed for security passing
        subProcessInstance.setRelatedClass(antelopeTaskInstance.getZebraProcessInstance().getRelatedClass());
        subProcessInstance.setRelatedKey(antelopeTaskInstance.getZebraProcessInstance().getRelatedKey());

        s.saveOrUpdate(subProcessInstance);
        t.commit();

        // map any inputs into the process
        mapTaskInputs((ZebraProcessInstance) antelopeTaskInstance.getProcessInstance(), subProcessInstance);

        // kick off the process
        zebra.startProcess(subProcessInstance);

    } catch (Exception e) {
        String emsg = "runTask failed to create Process " + processName;
        log.error(emsg, e);
        throw new RunTaskException(emsg, e);
    }

}

From source file:com.aprotrain.sl.dal.common.AbstractDao.java

@Override
public T saveOrUpdate(T a) {
    Session s = this.getSession();
    Transaction tx = s.beginTransaction();
    try {//from  ww  w.j a  v a2 s.com
        s.saveOrUpdate(a);
        tx.commit();

    } catch (Exception ex) {
        tx.rollback();
        throw ex;
    }
    s.close();
    return a;
}

From source file:com.aprotrain.sl.dal.common.AbstractDao.java

@Override
public T update(T a) {
    Session s = this.getSession();
    Transaction tx = s.beginTransaction();
    try {/*from   w ww  .j  a va2  s  .c  om*/
        s.saveOrUpdate(a);
        tx.commit();

    } catch (Exception ex) {
        tx.rollback();
        throw ex;
    }
    s.close();
    return a;
}

From source file:com.artech.prototype2.saver.dao.AbstractDao.java

public void saveOrUpdate(AbstractSUBD db, Type entity) {
    Session session = null;
    try {/*from w w w .j a v a2  s  . c o  m*/
        session = HibernateUtil.getSessionFactory(db).openSession();
        session.beginTransaction();
        session.saveOrUpdate(entity);
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
}

From source file:com.bahadirakin.dao.impl.BaseHibernateDAO.java

License:Apache License

public void saveOrUpdate(T entity) {
    if (entity == null) {
        throw new IllegalArgumentException("Entity must not be null");
    }/*from  w w w .  j  av a2 s  .c  o m*/

    try {
        Session session = this.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        session.saveOrUpdate(entity);
        transaction.commit();
    } catch (HibernateException e) {
        LOG.error("Error while saveOrUpdate Entity. M: " + e.getMessage() + " C: " + e.getCause(), e);
    }
}