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.enonic.cms.store.resource.FileResourceServiceImpl.java

License:Open Source License

private boolean doCreateFile(Session session, FileResourceName name, FileResourceData data) {
    String key = createKey(name);
    if (findEntity(session, key) != null) {
        return false;
    }// w  w  w.ja  v a2 s.  c o  m

    doCreateFolder(session, name.getParent());
    VirtualFileEntity entity = new VirtualFileEntity();
    entity.setKey(key);
    entity.setBlobKey(null);
    entity.setParentKey(createKey(name.getParent()));
    entity.setLength(0);
    entity.setName(name.getName());
    entity.setLastModified(System.currentTimeMillis());
    setBlob(entity, data != null ? data.getAsBytes() : new byte[0]);
    session.saveOrUpdate(entity);
    return true;
}

From source file:com.enonic.cms.store.resource.FileResourceServiceImpl.java

License:Open Source License

private boolean doCopyResourceFile(Session session, VirtualFileEntity from, FileResourceName to) {
    String toKey = createKey(to);
    VirtualFileEntity toEntity = findEntity(session, toKey);

    if (toEntity != null) {
        return false;
    }//from w ww. j a  v  a2 s  .co m

    doCreateFolder(session, to.getParent());
    toEntity = createNewEntity(from, to);
    session.saveOrUpdate(toEntity);
    return true;
}

From source file:com.eurodyn.uns.dao.hibernate.BaseHibernateDao.java

License:Mozilla Public License

protected void saveOrUpdate(Object obj, Session s) throws HibernateException {
    s.saveOrUpdate(obj);
}

From source file:com.example.app.model.DemoUserProfileDAO.java

License:Open Source License

/**
 * Save UserProfile./*from   www . j a  v a2  s  .  co m*/
 *
 * @param demoUserProfile the user profile to save.
 */
public void saveUserProfile(DemoUserProfile demoUserProfile) {
    beginTransaction();
    boolean success = false;
    try {
        final long id = demoUserProfile.getId();
        String name = demoUserProfile.getName().getLast() + ", " + demoUserProfile.getName().getFirst();
        String pictureName = name + " #" + id;
        final Session session = getSession();
        FileEntity picture = demoUserProfile.getPicture();
        if (picture != null) {
            pictureName += getExtensionWithDot(picture);
            TemporaryFileEntity tfe = null;
            if (picture instanceof TemporaryFileEntity)
                tfe = (TemporaryFileEntity) picture;
            ByteSource fileData = tfe != null ? tfe.asByteSource() : ByteSource.empty();
            // Ensure our picture file has a unique file name consistent with the profile.
            if (picture.getId() < 1) {
                final CmsSite site = demoUserProfile.getSite();
                final DirectoryEntity rootDirectory = FileSystemDirectory.getRootDirectory(site);
                DirectoryEntity parentDirectory = _fileSystemDAO.mkdirs(rootDirectory, null,
                        "UserProfilePictures");
                picture.setName(pictureName);

                picture = _fileSystemDAO.store(new StoreRequest(parentDirectory, picture, fileData)
                        .withCreateMode(overwrite).withRequest(Event.getRequest()));
                demoUserProfile.setPicture(picture);
            } else {
                EntityRetriever er = EntityRetriever.getInstance();
                picture = er.reattachIfNecessary(tfe != null ? tfe.getFileEntity() : picture);
                picture.setName(pictureName);
                _fileSystemDAO.store(new StoreRequest(picture, fileData).withCreateMode(overwrite)
                        .withRequest(Event.getRequest()));
                demoUserProfile.setPicture(picture); // In case we are cascading.
                if (tfe != null)
                    tfe.deleteStream();
            }
        }

        if (isTransient(demoUserProfile) || isAttached(demoUserProfile))
            session.saveOrUpdate(demoUserProfile);
        else
            session.merge(demoUserProfile);

        if (picture != null && id == 0) {
            // New user profile. Update picture name to include the ID
            pictureName = name + " #" + demoUserProfile.getId() + getExtensionWithDot(picture);
            picture.setName(pictureName);
            _fileSystemDAO.store(new StoreRequest(picture));
        }
        success = true;
    } catch (HibernateException ioe) {
        throw new RuntimeException("Unable to access filesystem.", ioe);
    } finally {
        if (success)
            commitTransaction();
        else
            recoverableRollbackTransaction();
    }
}

From source file:com.example.app.model.university.FacultyDAO.java

License:Open Source License

/**
 * Save the faculty./*from   www. j  a  v  a2s  . com*/
 *
 * @param faculty the faculty to save
 */
public void saveFaculty(Faculty faculty) {
    beginTransaction();
    boolean success = false;
    try {
        final Session session = getSession();
        session.saveOrUpdate(faculty);
        success = true;
    } finally {
        if (success)
            commitTransaction();
        else
            rollbackTransaction();
    }
}

From source file:com.example.app.model.UserProfileDAO.java

License:Open Source License

/**
 * Save UserProfile./*from w ww  . j a v  a  2  s  .c  o  m*/
 *
 * @param userProfile the user profile to save.
 */
public void saveUserProfile(UserProfile userProfile) {
    beginTransaction();
    boolean success = false;
    try {
        final long id = userProfile.getId();
        String name = userProfile.getName().getLast() + ", " + userProfile.getName().getFirst();
        String pictureName = name + " #" + id;
        final Session session = getSession();
        FileEntity picture = userProfile.getPicture();
        if (picture != null) {
            pictureName += getExtensionWithDot(picture);
            TemporaryFileEntity tfe = null;
            if (picture instanceof TemporaryFileEntity)
                tfe = (TemporaryFileEntity) picture;
            ByteSource fileData = tfe != null ? tfe.asByteSource() : ByteSource.empty();
            // Ensure our picture file has a unique file name consistent with the profile.
            if (picture.getId() < 1) {
                final CmsSite site = userProfile.getSite();
                final DirectoryEntity rootDirectory = FileSystemDirectory.getRootDirectory(site);
                DirectoryEntity parentDirectory = _fileSystemDAO.mkdirs(rootDirectory, null,
                        "UserProfilePictures");
                picture.setName(pictureName);

                picture = _fileSystemDAO.store(new StoreRequest(parentDirectory, picture, fileData)
                        .withCreateMode(overwrite).withRequest(Event.getRequest()));
                userProfile.setPicture(picture);
            } else {
                EntityRetriever er = EntityRetriever.getInstance();
                picture = er.reattachIfNecessary(tfe != null ? tfe.getFileEntity() : picture);
                picture.setName(pictureName);
                _fileSystemDAO.store(new StoreRequest(picture, fileData).withCreateMode(overwrite)
                        .withRequest(Event.getRequest()));
                userProfile.setPicture(picture); // In case we are cascading.
                if (tfe != null)
                    tfe.deleteStream();
            }
        }

        if (isTransient(userProfile) || isAttached(userProfile))
            session.saveOrUpdate(userProfile);
        else
            session.merge(userProfile);

        if (picture != null && id == 0) {
            // New user profile. Update picture name to include the ID
            pictureName = name + " #" + userProfile.getId() + getExtensionWithDot(picture);
            picture.setName(pictureName);
            _fileSystemDAO.store(new StoreRequest(picture));
        }
        success = true;
    } catch (HibernateException ioe) {
        throw new RuntimeException("Unable to access filesystem.", ioe);
    } finally {
        if (success)
            commitTransaction();
        else
            recoverableRollbackTransaction();
    }
}

From source file:com.example.maven.jaxrs.dao.PostgresDAO.java

public Boolean updatePerson(String FirstName, String LastName, int Age, long Person_Id) {
    try {//  www  . java  2  s. c om
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Query q = session.createQuery("from Person where Person_ID = :Person_Id");
        q.setParameter("Person_Id", Person_Id);
        Person person = (Person) q.list().get(0);

        person.setAge(Age);
        person.setFirstName(FirstName);
        person.setLastName(LastName);
        person.setId(Person_Id);
        session.saveOrUpdate(person);
        session.flush();
        session.close();
        return Boolean.TRUE;
    } catch (Exception e) {
        return Boolean.FALSE;
    }
}

From source file:com.example.maven.jaxws.dao.PostgresDAO.java

public boolean updatePerson(String FirstName, String LastName, int Age, long Person_Id) {
    try {//www  . j av a  2s .  c  om
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Query q = session.createQuery("from Person where Person_ID = :Person_Id");
        q.setParameter("Person_Id", Person_Id);
        Person person = (Person) q.list().get(0);

        person.setAge(Age);
        person.setFirstName(FirstName);
        person.setLastName(LastName);
        person.setId(Person_Id);
        session.saveOrUpdate(person);
        session.flush();
        session.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.facultyshowcase.app.model.ProfessorProfileDAO.java

License:Open Source License

/**
 * Save ProfessorProfile./*w ww  .j  a  va2s. com*/
 *
 * @param ProfessorProfile the user profile to save.
 */
@WithTransaction
public void saveProfessorProfile(ProfessorProfile ProfessorProfile) {
    try {
        final long id = ProfessorProfile.getId();
        String name = ProfessorProfile.getName().getLast() + ", " + ProfessorProfile.getName().getFirst();
        String pictureName = name + " #" + id;
        final Session session = getSession();
        FileEntity picture = ProfessorProfile.getPicture();
        if (picture != null) {
            pictureName += _getFileExtensionWithDot(picture);
            // Ensure our picture file has a unique file name consistent with the profile.
            if (picture.getId() < 1) {
                final CmsSite site = ProfessorProfile.getSite();
                final DirectoryEntity rootDirectory = FileSystemDirectory.getRootDirectory(site);
                DirectoryEntity parentDirectory = _fileSystemDAO.mkdirs(rootDirectory, null,
                        "ProfessorProfilePictures");
                picture.setName(pictureName);
                picture = _fileSystemDAO.newFile(parentDirectory, picture, FileSystemEntityCreateMode.truncate);
                ProfessorProfile.setPicture(picture);
            } else if (picture instanceof TemporaryFileEntity) {
                TemporaryFileEntity tfe = (TemporaryFileEntity) picture;
                EntityRetriever er = EntityRetriever.getInstance();
                picture = er.reattachIfNecessary(tfe.getFileEntity());
                picture.setName(pictureName);
                _fileSystemDAO.update(picture);
                _fileSystemDAO.setStream(picture, tfe.getStream(), true);
                ProfessorProfile.setPicture(picture); // In case we are cascading.
                tfe.deleteStream();
            }
        }

        ProfessorProfile.setLastModTime(new Date());
        if (isTransient(ProfessorProfile) || isAttached(ProfessorProfile))
            session.saveOrUpdate(ProfessorProfile);
        else
            session.merge(ProfessorProfile);

        if (picture != null && id == 0) {
            // New user profile. Update picture name to include the ID
            pictureName = name + " #" + ProfessorProfile.getId() + _getFileExtensionWithDot(picture);
            picture.setName(pictureName);
            _fileSystemDAO.update(picture);
        }

    } catch (IOException ioe) {
        throw new RuntimeException("Unable to access filesystem.", ioe);
    }
}

From source file:com.floreantpos.actions.DrawerAssignmentAction.java

License:Open Source License

private void performAssignment(Terminal terminal) throws Exception {
    Session session = null;
    Transaction tx = null;/*from w ww .j  a  v a2 s  .com*/

    try {
        UserListDialog dialog = new UserListDialog();
        dialog.pack();
        dialog.open();

        if (dialog.isCanceled()) {
            return;
        }

        User user = dialog.getSelectedUser();
        if (!user.isClockedIn()) {
            POSMessageDialog.showError("Can't assign drawer. Selected user is not clocked in.");
            return;
        }

        double drawerBalance = 0;
        CashDrawer cashDrawer = null;
        if (TerminalConfig.isEnabledMultiCurrency()) {
            List<Currency> currencyList = CurrencyUtil.getAllCurrency();

            if (currencyList.size() > 1) {
                MultiCurrencyAssignDrawerDialog multiCurrencyDialog = new MultiCurrencyAssignDrawerDialog(500,
                        currencyList);
                multiCurrencyDialog.pack();
                multiCurrencyDialog.open();

                if (multiCurrencyDialog.isCanceled()) {
                    return;
                }
                cashDrawer = multiCurrencyDialog.getCashDrawer();
                drawerBalance = multiCurrencyDialog.getTotalAmount();
            }
        } else {
            drawerBalance = NumberSelectionDialog2.takeDoubleInput(
                    Messages.getString("DrawerAssignmentAction.6"), //$NON-NLS-1$
                    Messages.getString("DrawerAssignmentAction.7"), 500); //$NON-NLS-1$
        }
        if (Double.isNaN(drawerBalance)) {
            return;
        }

        terminal.setAssignedUser(user);
        terminal.setCurrentBalance(drawerBalance);

        DrawerAssignedHistory history = new DrawerAssignedHistory();
        history.setTime(new Date());
        history.setOperation(DrawerAssignedHistory.ASSIGNMENT_OPERATION);
        history.setUser(user);

        session = TerminalDAO.getInstance().createNewSession();
        tx = session.beginTransaction();

        session.saveOrUpdate(terminal);
        session.save(history);

        if (cashDrawer != null) {
            session.saveOrUpdate(cashDrawer);
        }

        tx.commit();

        POSMessageDialog.showMessage(Messages.getString("DrawerAssignmentAction.8") + user.getFullName()); //$NON-NLS-1$

        putValue(Action.NAME, Messages.getString("DrawerAssignmentAction.9")); //$NON-NLS-1$

    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }

        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}