Example usage for org.hibernate Session getIdentifier

List of usage examples for org.hibernate Session getIdentifier

Introduction

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

Prototype

Serializable getIdentifier(Object object);

Source Link

Document

Return the identifier value of the given entity as associated with this session.

Usage

From source file:DAO.GenericDaoJpaImpl.java

public Map getAllMap() {
    List<T> lst = getAll();
    HashMap<PK, T> all = new HashMap<>();

    for (T obj : lst) {
        Session session = em.unwrap(Session.class);
        PK id = (PK) session.getIdentifier(obj);
        all.put(id, (T) obj);/*from   ww w.j  a  v  a 2s . co  m*/

    }
    return all;
}

From source file:edu.harvard.med.screensaver.db.GenericEntityDAOTest.java

License:Open Source License

public void testFlushAndClearSession() {
    genericEntityDao.runQuery(new Query() {
        public List execute(Session session) {
            Library library = new Library(_adminUser, "library", "library", ScreenType.SMALL_MOLECULE,
                    LibraryType.COMMERCIAL, 1, 1, PlateSize.WELLS_384);
            library.createWell(new WellKey(1, "A01"), LibraryWellType.EMPTY);
            genericEntityDao.saveOrUpdateEntity(library);
            genericEntityDao.flush();//from   w  w w .  jav a2  s.  c  o  m
            assertTrue(session.contains(library));
            assertEquals(3, session.getStatistics().getEntityCount());
            assertEquals(library.getLibraryId(), session.getIdentifier(library));
            genericEntityDao.clear();
            assertEquals(0, session.getStatistics().getEntityCount());
            assertFalse(session.contains(library));
            return null;
        }
    });

    assertNotNull(genericEntityDao.findEntityByProperty(Library.class, "libraryName", "library"));
    assertNotNull(genericEntityDao.findEntityById(Well.class, "00001:A01"));

}

From source file:mitm.common.security.keystore.dao.KeyStoreDAOTest.java

License:Open Source License

private static Long insertAction(String storeName, Session session, String alias) throws DatabaseException {
    try {/*from  w ww . j  a  v a2 s.  c om*/
        KeyStoreDAO dao = new KeyStoreDAOHibernate(storeName, session);

        File file = new File("test/resources/testdata/certificates/testcertificate.cer");

        X509Certificate certificate = TestUtils.loadCertificate(file);

        file = new File("test/resources/testdata/certificates/rim.cer");

        X509Certificate rimCertificate = TestUtils.loadCertificate(file);

        Certificate[] chain = new Certificate[] { certificate, rimCertificate };

        KeyStoreEntryHibernate entry = new KeyStoreEntryHibernate(storeName, certificate, chain, null, alias,
                new Date());

        dao.makePersistent(entry);

        return (Long) session.getIdentifier(entry);
    } catch (Exception e) {
        if (e instanceof DatabaseException) {
            throw (DatabaseException) e;
        }
        throw new DatabaseException(e);
    }
}

From source file:mitm.common.sms.hibernate.SMSGatewayDAOTest.java

License:Open Source License

private static Long addSMSAction(Session session, SMS sms, Date dateLastTry) throws DatabaseException {
    try {/*from w w  w  .jav a  2  s . c o  m*/
        SMSGatewayDAO dao = new SMSGatewayDAO(SessionAdapterFactory.create(session));

        SMSGatewayEntity entity = dao.addSMS(sms);

        if (dateLastTry != null) {
            entity.setDateLastTry(dateLastTry);
        }

        return (Long) session.getIdentifier(entity);
    } catch (Exception e) {
        if (e instanceof DatabaseException) {
            throw (DatabaseException) e;
        }
        throw new DatabaseException(e);
    }
}

From source file:monasca.api.infrastructure.persistence.hibernate.AlarmSqlRepoImpl.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public Map<String, Map<String, AlarmSubExpression>> findAlarmSubExpressionsForAlarmDefinition(
        String alarmDefinitionId) {
    logger.trace(ORM_LOG_MARKER, "findAlarmSubExpressionsForAlarmDefinition(...) entering");

    Session session = null;
    Transaction tx = null;//from  ww w. j  av a 2  s  .c o m
    Map<String, Map<String, AlarmSubExpression>> subAlarms = Maps.newHashMap();

    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        final Iterator<SubAlarmDb> rows = session.getNamedQuery(SubAlarmDb.Queries.BY_ALARMDEFINITION_ID)
                .setString("id", alarmDefinitionId).setReadOnly(true).iterate();

        while (rows.hasNext()) {

            final SubAlarmDb row = rows.next();
            final String alarmId = (String) session.getIdentifier(row.getAlarm());

            Map<String, AlarmSubExpression> alarmMap = subAlarms.get(alarmId);
            if (alarmMap == null) {
                alarmMap = Maps.newHashMap();
                subAlarms.put(alarmId, alarmMap);
            }

            final String id = row.getId();
            final String expression = row.getExpression();
            alarmMap.put(id, AlarmSubExpression.of(expression));
        }

        tx.commit();
        tx = null;

    } catch (Exception exp) {
        this.rollbackIfNotNull(tx);
        throw exp;
    } finally {
        if (session != null) {
            session.close();
        }
    }

    return subAlarms;
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmDefinitionSqlImpl.java

License:Apache License

@SuppressWarnings("unchecked")
private List<SubExpression> findSubExpressions(final Session session, final String alarmDefId) {

    final List<SubExpression> subExpressions = Lists.newArrayList();
    Map<String, Map<String, String>> dimensionMap = Maps.newHashMap();

    final DetachedCriteria subAlarmDefinitionCriteria = DetachedCriteria
            .forClass(SubAlarmDefinitionDb.class, "sad").createAlias("alarmDefinition", "ad")
            .add(Restrictions.conjunction(Restrictions.eqProperty("sad.alarmDefinition.id", "ad.id"),
                    Restrictions.eq("sad.alarmDefinition.id", alarmDefId)))
            .addOrder(Order.asc("sad.id")).setProjection(Projections.property("sad.id"));

    final ScrollableResults subAlarmDefinitionDimensionResult = session
            .createCriteria(SubAlarmDefinitionDimensionDb.class).add(Property
                    .forName("subAlarmDefinitionDimensionId.subExpression.id").in(subAlarmDefinitionCriteria))
            .setReadOnly(true).scroll(ScrollMode.FORWARD_ONLY);

    final ScrollableResults subAlarmDefinitionResult = session
            .getNamedQuery(SubAlarmDefinitionDb.Queries.BY_ALARMDEFINITION_ID).setString("id", alarmDefId)
            .setReadOnly(true).scroll(ScrollMode.FORWARD_ONLY);

    while (subAlarmDefinitionDimensionResult.next()) {

        final SubAlarmDefinitionDimensionDb dim = (SubAlarmDefinitionDimensionDb) subAlarmDefinitionDimensionResult
                .get()[0];//from w w w . jav  a 2  s.co m
        final SubAlarmDefinitionDimensionId id = dim.getSubAlarmDefinitionDimensionId();

        final String subAlarmId = (String) session.getIdentifier(id.getSubExpression());
        final String name = id.getDimensionName();
        final String value = dim.getValue();

        if (!dimensionMap.containsKey(subAlarmId)) {
            dimensionMap.put(subAlarmId, Maps.<String, String>newTreeMap());
        }
        dimensionMap.get(subAlarmId).put(name, value);

        session.evict(dim);
    }

    while (subAlarmDefinitionResult.next()) {
        final SubAlarmDefinitionDb def = (SubAlarmDefinitionDb) subAlarmDefinitionResult.get()[0];

        final String id = def.getId();
        final AggregateFunction function = AggregateFunction.fromJson(def.getFunction());
        final String metricName = def.getMetricName();
        final AlarmOperator operator = AlarmOperator.fromJson(def.getOperator());
        final Double threshold = def.getThreshold();
        final Integer period = def.getPeriod();
        final Integer periods = def.getPeriods();
        final Boolean deterministic = def.isDeterministic();

        Map<String, String> dimensions = dimensionMap.get(id);

        if (dimensions == null) {
            dimensions = Collections.emptyMap();
        }

        subExpressions.add(new SubExpression(id,
                new AlarmSubExpression(function, new MetricDefinition(metricName, dimensions), operator,
                        threshold, period, periods, deterministic)));

        session.evict(def);
    }

    subAlarmDefinitionDimensionResult.close();
    subAlarmDefinitionResult.close();

    return subExpressions;
}

From source file:net.databinder.models.hib.HibernateObjectModel.java

License:Open Source License

/**
 * Change the persistent object contained in this model.
 * Because this method establishes a persistent object ID, queries and binders
 * are removed if present./*from  ww w .  j  a va 2  s.c  om*/
 * @param object must be an entity contained in the current Hibernate session, or Serializable, or null
 */
public void setObject(T object) {
    unbind(); // clear everything but class, name
    objectClass = null;

    if (object != null) {
        objectClass = HibernateProxyHelper.getClassWithoutInitializingProxy(object);

        Session sess = Databinder.getHibernateSession(factoryKey);
        if (sess.contains(object))
            objectId = sess.getIdentifier(object);
        else if (retainUnsaved)
            retainedObject = (T) object;
        setTempModelObject(object); // skip calling load later
    }
}

From source file:net.databinder.models.hib.HibernateObjectModel.java

License:Open Source License

/**
 * Checks if the model is retaining an object this has since become a
 * persistent entity. If so, the ID is fetched and the reference discarded.  
 */// ww w  . j ava  2  s.  c  om
public void checkBinding() {
    if (!isBound() && retainedObject != null) {
        Session sess = Databinder.getHibernateSession(factoryKey);

        if (sess.contains(retainedObject)) {
            objectId = sess.getIdentifier(retainedObject);
            retainedObject = null;
        }
    }
}

From source file:np.com.drose.studentmanagementsystem.dao.impl.EmployeeDAOImpl.java

@Override
@Transactional/*from   ww w  .  j a v a2 s.  com*/
public int insertEmployee(Employee employee) {
    Session session = sessionfactory.openSession();
    Transaction tx = session.beginTransaction();
    session.saveOrUpdate(employee);
    tx.commit();
    Serializable id = session.getIdentifier(employee);
    session.close();
    return (Integer) id;
}

From source file:np.com.drose.studentmanagementsystem.dao.impl.ProgressDAOImpl.java

@Transactional
@Override//  w  w w . ja  v a 2  s . co m
public int insertProgress(Progress progress) {
    Session session = sessionFactory.openSession();
    org.hibernate.Transaction tx = session.beginTransaction();
    session.saveOrUpdate(progress);
    tx.commit();
    Serializable id = session.getIdentifier(progress);
    session.close();
    return (Integer) id;
}