Example usage for org.hibernate Session load

List of usage examples for org.hibernate Session load

Introduction

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

Prototype

void load(Object object, Serializable id);

Source Link

Document

Read the persistent state associated with the given identifier into the given transient instance.

Usage

From source file:com.github.snd297.yp.proxies.persistence.InstanceofTest.java

License:Apache License

@Test
public void notInstanceofASquare() {
    Session session = null;
    Transaction trx = null;/*from w w  w.jav  a2  s  .c  o m*/
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        trx = session.beginTransaction();

        Shape loadedSquare = (Shape) session.load(Shape.class, squareId);
        assertFalse(loadedSquare instanceof Square);
        assertTrue(loadedSquare instanceof HibernateProxy);

        Shape gotSquare = (Shape) session.get(Shape.class, squareId);
        assertSame(loadedSquare, gotSquare);

        trx.commit();
    } catch (RuntimeException e) {
        HibernateUtil.rollbackQuietly(trx);
        throw e;
    } finally {
        HibernateUtil.closeQuietly(session);
    }
}

From source file:com.globalsight.everest.workflowmanager.WorkflowAdditionMDB.java

License:Apache License

private void addTargetPagesToWorkflows(HashMap p_pages, List p_workflows, Job p_job)
        throws WorkflowManagerException {
    SourcePage sourcePage = null;/*from   ww  w. j  a  va  2 s.c  o m*/

    Session session = null;
    Transaction transaction = null;

    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
        HashMap targetPages = new HashMap(p_pages);

        // get the source page from the map
        sourcePage = (SourcePage) targetPages.remove(p_job.getL10nProfile().getSourceLocale().getIdAsLong());
        Vector toplinkTargetPages = PagePersistenceAccessor.getTargetPages(sourcePage.getId());
        HashMap mapTargetPages = convertVectorIntoMap(toplinkTargetPages);
        Iterator it = p_workflows.iterator();

        while (it.hasNext()) {
            Workflow workflow = (Workflow) it.next();

            Workflow wfClone = (WorkflowImpl) session.load(WorkflowImpl.class, workflow.getIdAsLong());
            TargetPage targetPage = (TargetPage) targetPages.get(workflow.getTargetLocale().getIdAsLong());
            TargetPage toplinkTargetPage = (TargetPage) mapTargetPages.get(targetPage.getIdAsLong());
            TargetPage targetPageClone = (TargetPage) session.load(TargetPage.class,
                    toplinkTargetPage.getIdAsLong());

            wfClone.addTargetPage(targetPageClone);
            session.update(wfClone);
        }

        transaction.commit();
    } catch (Exception pe) {
        if (transaction != null) {
            transaction.rollback();
        }
        c_logger.error("Unable to add workflows to given job" + pe);
        String args[] = new String[1];
        args[0] = Long.toString(sourcePage.getId());

        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_ADD_WORKFLOW, args, pe);
    } finally {
        if (session != null) {
            // session.close();
        }
    }
}

From source file:com.globalsight.persistence.hibernate.HibernateUtil.java

License:Apache License

/**
 * Return the persistent instance of the given entity class with the given
 * identifier, assuming that the instance exists. This method might return a
 * proxied instance that is initialized on-demand, when a non-identifier
 * method is accessed. <br>/*from   w  ww  .  ja  v a 2 s  . c  om*/
 * <br>
 * You should not use this method to determine if an instance exists (use
 * <tt>get()</tt> instead). Use this only to retrieve an instance that you
 * assume exists, where non-existence would be an actual error.
 * 
 * @param clazz
 *            a persistent class
 * @param id
 *            a valid identifier of an existing persistent instance of the
 *            class
 * @return the persistent instance or proxy
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static <T> T load(Class<T> clazz, Serializable id) throws Exception {
    T result = null;

    if (clazz != null) {
        Session session = null;
        try {
            session = getSession();
            result = (T) session.load(clazz, id);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    return result;
}

From source file:com.googlecode.sarasvati.example.db.NodeTask.java

License:Open Source License

@Override
public void execute(Engine engine, NodeToken token) {
    HibEngine hibEngine = (HibEngine) engine;

    Session session = hibEngine.getSession();

    TaskState open = (TaskState) session.load(TaskState.class, 0);
    Task newTask = new Task((HibNodeToken) token, getTaskName(), getTaskDesc(), open);
    session.save(newTask);//  ww w.j av a 2  s  .c  o  m

    Env env = token.getEnv();
    env.setLongAttribute(newTask.getName(), env.getLongAttribute(newTask.getName()) + 1);

    env = token.getProcess().getEnv();
    env.setLongAttribute(newTask.getName(), env.getLongAttribute(newTask.getName()) + 1);
}

From source file:com.gq.meter.xchange.filter.GateKeeperFilter.java

/**
 * This method used to validate the un marshalled GQMeterResponse data
 * /*from   w w  w. ja  v  a 2s . c om*/
 * @param gqmResponse
 */
public void process(GQMeterResponse gqmResponse) {
    // TODO : validate all the failure scenarios
    Session session = null;
    MeterRun meterRun = null;

    // parse the object and get the protocols and save them for now.....
    GQGateKeeperConstants.logger.info("Validating the unmarshlled GQMeterResponse data");

    String fwdUrl = null;
    String protocolId = null;
    String meterId = gqmResponse.getGqmid();

    Date recordDT = gqmResponse.getRecDttm();

    short scanned = gqmResponse.getAssetScanned();// total asset scanned from the input file
    short discovered = gqmResponse.getAssetDiscovered();// total asset actually discovered using GQMeter
    long runTimeMs = gqmResponse.getRunTimeMiliSeconds();

    GQGateKeeperConstants.logger.info(" GQMeter ID : " + meterId);
    GQGateKeeperConstants.logger.info(" Total asset scanned from the input file : " + scanned);
    GQGateKeeperConstants.logger.info(" Total asset actually discovered using GQMeter : " + discovered);

    // TODO : Analyze the scenario in which the assets discovered value may become 0.
    // TODO : Sort out the scenarios and decide whether to consider it as a run or not.

    try {
        // This step will read hibernate.cfg.xml and prepare hibernate for use
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        // ---------------------------------------------------------------------------------------------------------//
        GQGateKeeperConstants.logger.info("ENTERPRISEMETER");
        // checking meterid from the enterprisemeter table
        String hql = "FROM EnterpriseMeter WHERE meter_id = :METER_ID";
        Query query = session.createQuery(hql);
        query.setParameter("METER_ID", meterId);
        List<EnterpriseMeter> entMeterResult = query.list();

        // what if the entMeterResult size is more than 1
        // entMeterResult size cannot be more than 1, meter_id is always unique
        if (entMeterResult.size() == 0) {
            GQGateKeeperConstants.logger
                    .info("The meterid from the JSON != with the database value, Data insertion restricted");
            session.close();
            return;
        }

        String enterpriseId = entMeterResult.get(0).getEnterpriseId();
        String gqmId = gqmResponse.getGqmid();
        // Concatenating the enterpriseId with the meterId
        // The purpose of doing this is to invoke enterprise specific DB
        // instance on the GQEDProcessor application - tenant_identifier
        gqmId = enterpriseId + "_" + gqmId;
        gqmResponse.setGqmid(gqmId);
        // ---------------------------------------------------------------------------------------------------------//
        // protocol should be entered into DB in lower case only - Type safety
        protocolId = entMeterResult.get(0).getProtocolId();

        List<ProtocolData> pdList = gqmResponse.getAssetInformationList();
        List<ProtocolData> pdValidList = new LinkedList<ProtocolData>();
        if (!protocolId.equals(GQGateKeeperConstants.PROTOCOL_IT)) {

            for (ProtocolData pdData : pdList) {
                GQGateKeeperConstants.logger
                        .info("protocolId : " + protocolId + " from JSON : " + pdData.getProtocol().toString());
                if (pdData.getProtocol().toString().toLowerCase().trim().equals(protocolId)) {
                    pdValidList.add(pdData);
                    GQGateKeeperConstants.logger.info("valid meter data has been added into pdValidList");
                }
            } // for loop ends
              // Actual number of assets that are matches with the type of meter
              // for which the enterprise is registered for.
        } else {
            pdValidList.addAll(pdList);
        }
        discovered = (short) pdValidList.size();
        gqmResponse.setAssetDiscovered(discovered);
        GQGateKeeperConstants.logger.info(" Total number of assets after meter validation***  : " + discovered
                + " : " + pdValidList.size());
        // ---------------------------------------------------------------------------------------------------------//
        // checking meterid from the GateKeeper table
        hql = "FROM GateKeeper WHERE enterprise_id = :ENTERPRISE_ID";// prepared stmt
        GQGateKeeperConstants.logger.info("GATEKEEPER ::: " + hql);
        query = session.createQuery(hql);
        query.setParameter("ENTERPRISE_ID", enterpriseId);
        List<GateKeeper> gatekeeperResult = query.list();
        GQGateKeeperConstants.logger.info("gatekeeperResult : : : " + gatekeeperResult.toString());
        // what if the gatekeeperResult size is more than 1
        // gatekeeperResult size cannot be more than 1, meter_id is always unique
        if (gatekeeperResult == null) {
            System.out.println(
                    "The meterid from the JSON != with the database GateKeeper value, Data insertion restricted");
            session.close();
            return;
        }

        // char checkCondition = gatekeeperResult.get(0).getChkCndtn();
        // int scanRemaining = gatekeeperResult.get(0).getScnRmng();
        // if (checkCondition == 'c') {
        // GQGateKeeperConstants.logger.info("Validating the license based on scan reamining");
        // // Check total asset scanned allowed
        // if (scanRemaining < discovered || scanRemaining <= 0) {
        // GQGateKeeperConstants.logger.info("Scanning is not allowed, exceeds the license limit");
        // session.close();
        // return;
        // }
        // }
        // else if (checkCondition == 'e') {
        GQGateKeeperConstants.logger.info("Validating the license based expiry date");
        // Compare today date and expired date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String expirydDate = sdf.format(gatekeeperResult.get(0).getExpDttm());
        String currDate = sdf.format(new Date());
        GQGateKeeperConstants.logger.info("Curr date : " + currDate + " expirydate : " + expirydDate);
        int dateValue = expirydDate.compareTo(currDate);

        GQGateKeeperConstants.logger.info("==============  " + dateValue);
        if (dateValue == -1) {
            GQGateKeeperConstants.logger.info("License is expired");
            GQGateKeeperConstants.logger
                    .info("The date is expired please renewal the license, Data insertion restricted");
            session.close();
            return;
        } else if (dateValue == 0) {
            GQGateKeeperConstants.logger.info("Today license is going to expire : " + expirydDate);
        } else if (dateValue == 1) {
            GQGateKeeperConstants.logger.info("The license wil expiry on : " + expirydDate);
        }
        // }

        // scanRemaining = scanRemaining - discovered;
        // GQGateKeeperConstants.logger.info("Scan remain : " + scanRemaining);
        // update gatekeeper table once decremented the count

        GateKeeper gateKeeper = (GateKeeper) session.load(GateKeeper.class,
                gatekeeperResult.get(0).getEnterpriseId());
        // gateKeeper.setScnRmng(scanRemaining);

        // ---------------------------------------------------------------------------------------------------------//
        GQGateKeeperConstants.logger.info("ENTERPRISE" + enterpriseId.trim());
        String enthql = "FROM Enterprise WHERE enterprise_id = :ENTERPRISE_ID";

        GQGateKeeperConstants.logger.info("ENTERPRISE ::: " + enthql);
        Query entQuery = session.createQuery(enthql);
        entQuery.setParameter("ENTERPRISE_ID", enterpriseId.trim());
        List<Enterprise> entResult = entQuery.list();
        GQGateKeeperConstants.logger
                .info("GATEKEEPER*****************************" + entResult.get(0).getAns1());
        // what if the entMeterResult size is more than 1
        // entMeterResult size cannot be more than 1, meter_id is always unique
        if (entResult.size() == 0) {
            GQGateKeeperConstants.logger
                    .info("The meterid from the JSON != with the database value, Data insertion restricted");
            session.close();
            return;
        }

        // Check whether to store or forward the data to GQEDP
        char storeOrForward = entResult.get(0).getStoreFwd();
        // If fwd then get the fwd URL and pass the json to this
        if (storeOrForward == 'f') {
            fwdUrl = entResult.get(0).getFwdUrl();
            if (fwdUrl == null || fwdUrl == "") {
                GQGateKeeperConstants.logger.info("Forward URL is null/empty in the DB");
                session.close();
                return;
            }
        } else {
            // Local GQEDP application URL
            fwdUrl = GQGateKeeperConstants.GQEDP_URL;
        }

        // ---------------------------------------------------------------------------------------------------------//
        // inserting runid - auto incremented
        GQGateKeeperConstants.logger.debug("Meter Run Details are:" + meterId + "\n" + recordDT + "\n" + scanned
                + "\n" + discovered + "\n" + runTimeMs);
        meterRun = new MeterRun(meterId, recordDT, scanned, discovered, runTimeMs);
        Long runid = (Long) session.save(meterRun);
        session.getTransaction().commit();

        gqmResponse.setRunid(runid);
        // TODO: solve the error which occured while saving the data into asset_err table
        // Inserting error information into asset_err table
        GqMeterErrorInfo.insertErrorInfo(gqmResponse.getErrorInformationList(), gqmResponse.getRunid());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (session.isOpen()) {
                session.flush();
                session.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } // finally ends
    if (protocolId != null) {
        GQDataXchangeController xChange = new GQDataXchangeController();
        xChange.sendToEntDataProcessor(fwdUrl, protocolId, gqmResponse);
    }
}

From source file:com.guestbook.service.impl._GenericDaoHibernateImpl.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from w w w  .jav a2s.co  m
public void delete(final Integer id) {
    // Delete must take place within a HibernateCallback so that the object's associated
    //   Session can be retrieved; a simple getHibernateTemplate().delete() causes
    //   Session conflicts with the OpenSessionInViewFilter.
    @SuppressWarnings("rawtypes")
    HibernateCallback callback = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Object entity = session.load(clazz, id);
            session.delete(entity);
            return null;
        }
    };
    getHibernateTemplate().execute(callback);
}

From source file:com.hibernate.dao.AutomovilDAO.java

public void borraAutomovil(int idAutomovil) {
    Transaction trns = null;//from  www  .  j  a v a  2s. c  o m
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        Automovil automovil = (Automovil) session.load(Automovil.class, new Integer(idAutomovil));
        session.delete(automovil);
        session.getTransaction().commit();
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

From source file:com.hibernate.dao.ClienteDAO.java

public void borraCliente(int idCliente) {
    Transaction trns = null;//from   www  .j a  va 2s  .co  m
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        Cliente cliente = (Cliente) session.load(Cliente.class, new Integer(idCliente));
        session.delete(cliente);
        session.getTransaction().commit();
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

From source file:com.hibernate.dao.DireccionDAO.java

public void borraProvedor(int idDireccion) {
    Transaction trns = null;/*from  ww  w  . j  a  v a  2  s .  co  m*/
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        Direccion direccion = (Direccion) session.load(Direccion.class, new Integer(idDireccion));
        session.delete(direccion);
        session.getTransaction().commit();
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

From source file:com.hibernate.dao.PedidoDAO.java

public void borraPedido(int idPedido) {
    Transaction trns = null;/*  w w  w . j av a 2s  .  co m*/
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        Pedido pedido = (Pedido) session.load(Pedido.class, new Integer(idPedido));
        session.delete(pedido);
        session.getTransaction().commit();
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}