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:edu.ku.brc.specify.datamodel.busrules.DivisionBusRules.java

License:Open Source License

/**
 * /*w w  w  . j a v  a 2  s.c  om*/
 */
private void addNewDivision() {
    if (!checkForParentSave(formViewObj, Institution.getClassTableId())) {
        return;
    }

    if (!askForExitonChange("ASK_TO_ADD_DIV")) {
        return;
    }
    UIRegistry.writeSimpleGlassPaneMsg(UIRegistry.getResourceString("BUILD_DIV"), 20); // I18N
    isOKToCont = true;
    final AppContextMgr acm = AppContextMgr.getInstance();

    UIRegistry.loadAndPushResourceBundle("specifydbsetupwiz");

    final SpecifyDBSetupWizard wizardPanel = new SpecifyDBSetupWizard(SpecifyDBSetupWizard.WizardType.Division,
            null);

    String bldTitle = UIRegistry.getResourceString("CREATEDIV");
    final CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(), "", true,
            CustomDialog.NONE_BTN, wizardPanel);
    dlg.setCustomTitleBar(bldTitle);
    wizardPanel.setListener(new SpecifyDBSetupWizard.WizardListener() {
        @Override
        public void cancelled() {
            isOKToCont = false;
            dlg.setVisible(false);
        }

        @Override
        public void finished() {
            dlg.setVisible(false);
        }

        @Override
        public void hide() {
            dlg.setVisible(false);
        }

        @Override
        public void panelChanged(String title) {
            dlg.setTitle(title);
        }

        @Override
        public void helpContextChanged(String helpTarget) {

        }
    });
    UIHelper.centerAndShow(dlg);

    UIRegistry.popResourceBundle();

    if (!isOKToCont) {
        UIRegistry.clearSimpleGlassPaneMsg();
        return;
    }

    wizardPanel.processDataForNonBuild();

    final BuildSampleDatabase bldSampleDB = new BuildSampleDatabase();
    final ProgressFrame progressFrame = bldSampleDB.createProgressFrame(bldTitle);
    progressFrame.turnOffOverAll();

    progressFrame.setProcess(0, 17);
    progressFrame.setProcessPercent(true);
    progressFrame.getCloseBtn().setVisible(false);
    progressFrame.setAlwaysOnTop(true);
    progressFrame.adjustProgressFrame();

    UIHelper.centerAndShow(progressFrame);

    SwingWorker<Integer, Integer> bldWorker = new SwingWorker<Integer, Integer>() {
        private int steps = 0;
        private Division newDivision = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @SuppressWarnings("cast")
        @Override
        protected Integer doInBackground() throws Exception {
            firePropertyChange(PROGRESS, 0, ++steps);

            bldSampleDB.setDataType(acm.getClassObject(DataType.class));

            Division curDivCached = acm.getClassObject(Division.class);
            Discipline curDispCached = acm.getClassObject(Discipline.class);
            Collection curCollCached = acm.getClassObject(Collection.class);

            acm.setClassObject(Division.class, null);
            acm.setClassObject(Discipline.class, null);
            acm.setClassObject(Collection.class, null);

            // I don't think this is necessary
            // rods - 08/27/09
            //UIFieldFormatterMgr.getInstance().reset();
            //DataObjFieldFormatMgr.getInstance().reset();

            Session session = null;
            try {
                session = HibernateUtil.getNewSession();
                DataProviderSessionIFace hSession = new HibernateDataProviderSession(session);

                Institution inst = (Institution) formViewObj.getMVParent().getMultiViewParent().getData();
                Institution institution = hSession.get(Institution.class, inst.getId());
                SpecifyUser specifyAdminUser = (SpecifyUser) acm.getClassObject(SpecifyUser.class);
                Properties props = wizardPanel.getProps();

                institution = (Institution) session.merge(institution);
                specifyAdminUser = (SpecifyUser) hSession
                        .getData("FROM SpecifyUser WHERE id = " + specifyAdminUser.getId());

                bldSampleDB.setSession(session);

                DisciplineType dispType = (DisciplineType) props.get("disciplineType");
                newDivision = bldSampleDB.createEmptyDivision(institution, dispType, specifyAdminUser, props,
                        true, false, true);

                acm.setClassObject(Division.class, curDivCached);
                acm.setClassObject(Discipline.class, curDispCached);
                acm.setClassObject(Collection.class, curCollCached);

            } catch (Exception ex) {
                ex.printStackTrace();

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

            bldSampleDB.setDataType(null);

            return null;
        }

        @Override
        protected void done() {
            super.done();

            progressFrame.setVisible(false);
            progressFrame.dispose();

            if (newDivision != null) {
                List<?> dataItems = null;

                FormViewObj instFVO = formViewObj.getMVParent().getMultiViewParent()
                        .getCurrentViewAsFormViewObj();
                Institution inst = (Institution) instFVO.getDataObj();
                DataProviderSessionIFace pSession = null;
                try {
                    pSession = DataProviderFactory.getInstance().createSession();

                    inst = (Institution) pSession.getData("FROM Institution WHERE id = " + inst.getId());
                    inst.forceLoad();

                    acm.setClassObject(Institution.class, inst);

                    dataItems = pSession.getDataList("FROM Institution");
                    if (dataItems.get(0) instanceof Object[]) {
                        Vector<Object> dataList = new Vector<Object>();
                        for (Object row : dataItems) {
                            Object[] cols = (Object[]) row;
                            Institution div = (Institution) cols[0];
                            div.forceLoad();
                            dataList.add(div);
                        }
                        dataItems = dataList;
                    }

                } catch (Exception ex) {
                    System.err.println(ex);
                    ex.printStackTrace();

                } finally {
                    if (pSession != null) {
                        pSession.close();
                    }
                }

                // Not needed now that we are exiting
                //int curInx = instFVO.getRsController().getCurrentIndex();
                //instFVO.setDataObj(dataItems);
                //instFVO.getRsController().setIndex(curInx);

            } else {
                // error creating
            }
            UIRegistry.clearSimpleGlassPaneMsg();

            UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
            CommandDispatcher.dispatch(new CommandAction(BaseTask.APP_CMD_TYPE, BaseTask.APP_REQ_EXIT));

        }
    };

    bldWorker.execute();

}

From source file:edu.ku.brc.specify.dbsupport.CollectionAutoNumber.java

License:Open Source License

@Override
protected String getHighestObject(final UIFieldFormatterIFace formatter, final Session session,
        final String value, final Pair<Integer, Integer> yearPos, final Pair<Integer, Integer> pos)
        throws Exception {
    boolean doDebug = false;

    Collection currCol = AppContextMgr.getInstance().getClassObject(Collection.class);
    AutoNumberingScheme catNumScheme = currCol.getNumberingSchemesByType(CollectionObject.getClassTableId());
    if (catNumScheme == null) {
        throw new RuntimeException("The Catalog Numbering Scheme cannot be null! Collection Table ID: "
                + CollectionObject.getClassTableId());
    }/* w w w.  j a v a  2s .  c  o  m*/
    catNumScheme = (AutoNumberingScheme) session.merge(catNumScheme);

    if (doDebug)
        System.out.println("CatNumScheme: " + catNumScheme.getSchemeName());

    Vector<Integer> ids = new Vector<Integer>();
    for (Collection collection : catNumScheme.getCollections()) {
        if (doDebug)
            System.out.println(
                    "adding ID: " + collection.getCollectionId() + "  " + collection.getCollectionName());
        ids.add(collection.getCollectionId());
    }

    StringBuilder sb = new StringBuilder(
            "SELECT CatalogNumber FROM collectionobject WHERE CollectionMemberID IN (");
    Connection conn = null;
    Statement stmt = null;

    for (int i = 0; i < ids.size(); i++) {
        if (i > 0)
            sb.append(',');
        sb.append(ids.get(i));
    }
    sb.append(") ORDER BY CatalogNumber DESC");
    log.debug(sb.toString());

    try {
        conn = DBConnection.getInstance().getConnection();
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = stmt.executeQuery(sb.toString());

        String catNum = null;
        if (rs.next()) {
            catNum = rs.getString(1);
        }
        rs.close();

        return catNum;

    } catch (SQLException e) {
        edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(CollectionAutoNumber.class, e);
        log.error("Exception caught: " + e); //$NON-NLS-1$
        e.printStackTrace();

    } finally {
        try {
            if (stmt != null)
                stmt.close();

        } catch (SQLException e) {
            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(CollectionAutoNumber.class, e);
            log.error("Exception caught: " + e.toString()); //$NON-NLS-1$
            e.printStackTrace();
        }
    }

    return null;
}

From source file:edu.ku.brc.specify.treeutils.HibernateTreeDataServiceImpl.java

License:Open Source License

/**
 * Merges object with session.//w  ww.  ja  v  a 2 s . c  om
 * @param session the session
 * @param object the object to be merged
 * @return a new object after the merge.
 */
private Object mergeIntoSession(final Session session, final Object object) {
    return session.merge(object);
}

From source file:edu.nps.moves.mmowgli.hibernate.HSessionAccessor.java

License:Open Source License

static <T> T merge(T obj, Session sess)
//-------------------------------------
{
    MSysOut.println(HIBERNATE_SESSION_LOGS, "Session merge of " + obj.getClass().getSimpleName() + " "
            + obj.hashCode() + " session: " + sess.hashCode());
    return (T) sess.merge(obj);
}

From source file:edu.scripps.fl.pubchem.PubChemDB.java

License:Apache License

public static void saveXRefs(Session session, PCAssay assay) {
    for (PCAssayXRef assayXRef : assay.getAssayXRefs()) {
        XRef xref = assayXRef.getXRef();
        //         System.out.println(String.format("AID = %s, db = %s, xrefid = %s", assay.getAID(), xref.getDatabase(), xref.getXRefId()));
        Criteria criteria = session.createCriteria(XRef.class);
        criteria.add(Restrictions.eq("database", xref.getDatabase()));
        criteria.add(Restrictions.eq("XRefId", xref.getXRefId()));
        XRef dbxref = (XRef) criteria.uniqueResult();
        if (null == dbxref)
            session.save(xref);/*from  w w  w.ja  v a  2s  . c  om*/
        else {
            xref.setId(dbxref.getId());
            xref = (XRef) session.merge(xref);
        }
    }
}

From source file:edu.scripps.fl.pubchem.PubChemFactory.java

License:Apache License

public void populateAssayResults(Session session, PCAssay assay, InputStream is) throws Exception {
    long counter = 0L;
    PCAssayColumn activeColumn = assay.getActiveColumn();
    List<PCAssayColumn> testedCols = assay.getTestedColumns();

    CsvReader reader = new CsvReader(new BufferedReader(new InputStreamReader(is)), ',');
    reader.readHeaders();/*from   w  ww .java  2 s .c o m*/
    String[] headers = reader.getHeaders();

    Transaction trx = session.beginTransaction();
    while (reader.readRecord()) {

        String[] values = reader.getValues();

        String[] sids = reader.get("PUBCHEM_SID").split("\\s*,\\s*");

        if (sids.length > 1) {
            log.warn(String.format("AID %s has %s SIDS on a line", assay.getAID(), sids.length));
        }

        for (String sid : sids) {

            PCAssayResult result = new PCAssayResult();

            result.setSID(Long.parseLong(sid));

            String cid = reader.get("PUBCHEM_CID");
            if (!"".equals(cid))
                result.setCID(Long.parseLong(cid));

            result.setComments(reader.get("PUBCHEM_ASSAYDATA_COMMENT"));

            int outcome = Integer.parseInt(reader.get("PUBCHEM_ACTIVITY_OUTCOME"));
            result.setOutcome(getOutcome(outcome));

            String score = reader.get("PUBCHEM_ACTIVITY_SCORE");
            if (!"".equals(score))
                result.setRankScore(Integer.parseInt(score));

            result.setURL(reader.get("PUBCHEM_ACTIVITY_URL"));

            result.setXref(reader.get("PUBCHEM_EXT_DATASOURCE_REGID"));

            // if a dose response assay with a marked activeConcentration
            if ("confirmatory".equals(assay.getActivityOutcomeMethod()) && activeColumn != null) {
                String actConc = reader.get("" + activeColumn.getTID());
                if (!"".equals(actConc)) {
                    result.setPrimaryValue(Double.valueOf(actConc));
                    result.setPrimaryColumn(activeColumn);

                    PCAssayColumn qualCol = assay.getQualifierColumn();
                    if (qualCol != null) {
                        String qual = reader.get("" + qualCol.getTID()); // get(String)
                        if (!"".equals(qual))
                            result.setQualifier(qual);
                    }
                }

            } else if ("screening".equals(assay.getActivityOutcomeMethod()) && testedCols.size() > 0) {
                PCAssayColumn testedCol = testedCols.get(0);
                String value = reader.get("" + testedCol.getTID());
                result.setPrimaryColumn(testedCol);
                if (!"".equals(value))
                    if ("float".equals(testedCol.getType()) || "int".equals(testedCol.getType()))
                        result.setPrimaryValue(Double.parseDouble(value));
                    else
                        result.setPrimaryValueAsString(value);
            }
            // put all testedConcentration columns into an ordered array.
            // Interested in numbers here only.
            result.getTestedValues().clear();
            for (int ii = 0; ii < testedCols.size(); ii++) {
                String value = reader.get("" + testedCols.get(ii).getTID());
                try {
                    Double dbl = Double.parseDouble(value);
                    result.getTestedValues().set(ii, dbl);
                } catch (NumberFormatException ex) {
                    // if not a number then don't worry about it.
                }
            }

            List<String> list = result.getAllValues();
            list.clear();
            for (PCAssayColumn col : assay.getColumns()) {
                if (col.getTID() > 0) { // not the outcome and score
                    String value = reader.get("" + col.getTID());
                    list.set(col.getTID() - 1, value);
                }
            }

            result.setAssay(assay);

            session.save(result);

            if (++counter % 100 == 0) {
                trx.commit();
                session.clear(); // else huge build up of hibernate memory
                // cache
                trx = session.beginTransaction();
            }
            if (counter % 10000 == 0)
                log.debug(String.format("AID %s: processed %s results", assay.getAID(), counter));
        }
    }
    log.debug(String.format("Processed AID: %s, contained %s results", assay.getAID(), counter));
    assay = (PCAssay) session.merge(assay);
    assay.setVersionChanged(false);
    session.save(assay);
    trx.commit();
}

From source file:eionet.webq.dao.ProjectFileStorageImpl.java

License:Mozilla Public License

/**
 * Updates all fields.//from  w  w  w . java  2s. co  m
 *
 * @param projectFile project file
 */
private void fullUpdate(ProjectFile projectFile) {
    Session currentSession = getCurrentSession();
    projectFile.setUpdated(new Timestamp(System.currentTimeMillis()));
    currentSession.merge(projectFile);
    currentSession.flush();
}

From source file:es.emergya.bbdd.dao.BandejaEntradaHome.java

License:Open Source License

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Throwable.class)
public boolean saveOrUpdate(Inbox b) {
    Session currentSession = getSession();
    currentSession.flush();/*from  w w w .  j  av  a2 s .co  m*/
    currentSession.saveOrUpdate(currentSession.merge(b));
    return true;

}

From source file:es.emergya.bbdd.dao.CapaInformacionHome.java

License:Open Source License

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Throwable.class)
public boolean saveOrUpdate(CapaInformacion p) {
    if (p == null) {
        return false;
    }/*from  w  ww  .  j  av a  2  s .  c  o m*/

    CapaInformacion entity = null;
    try {
        Session currentSession = getSession();
        if (p.getId() != null && this.get(p.getId()) != null) {
            entity = (CapaInformacion) currentSession.merge(p);
        }

        if (entity == null) {
            entity = p;
        }

        if (p.getOrden() == null && entity.getOrden() == null) {
            entity.setOrden(getTotal() + 1);
        }

        currentSession.saveOrUpdate(entity);

        return true;
    } catch (Throwable t) {
        log.error(t, t);
        return false;
    }
}

From source file:es.emergya.bbdd.dao.FlotaHome.java

License:Open Source License

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Throwable.class)
public boolean saveOrUpdate(Flota f) {
    boolean res = false;
    if (f == null)
        return res;
    try {/*from   w ww.  j a  v a2  s .  c  o  m*/
        log.debug("Saving " + f);
        final Set<Rol> roles = f.getRoles();
        final Set<Recurso> recurso = f.getRecurso();
        removeRecursos(f);
        removeRoles(f);
        Session currentSession = getSession();
        currentSession.clear();

        Flota entity = null;

        if (f.getId() != null && this.get(f.getId()) != null)
            entity = (Flota) currentSession.merge(f);
        else
            entity = f;
        if (recurso != null)
            for (Recurso r : recurso) {
                r = (Recurso) currentSession.get(Recurso.class, r.getId());
                if (r != null) {
                    r.setFlotas(entity);
                    currentSession.saveOrUpdate(r);
                }
            }

        if (roles != null)
            for (Rol r : roles) {
                Rol rentity = (Rol) currentSession.get(Rol.class, r.getId());
                if (rentity != null) {
                    rentity.getFlotas().add(entity);
                    currentSession.saveOrUpdate(rentity);
                }
            }

        currentSession.saveOrUpdate(entity);
    } catch (Throwable t) {
        log.error(t, t);
        return false;
    }
    return true;
}