Example usage for org.hibernate Session byId

List of usage examples for org.hibernate Session byId

Introduction

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

Prototype

<T> IdentifierLoadAccess<T> byId(Class<T> entityClass);

Source Link

Document

Create an IdentifierLoadAccess instance to retrieve the specified entity by primary key.

Usage

From source file:Storage.java

License:Open Source License

public static Episode findEpisode(int id) {
    Session session = factory.openSession();
    Transaction tx = null;// www.  ja  v  a  2  s  .co m
    try {
        tx = session.beginTransaction();
        Episode episode = (Episode) session.byId(Episode.class).load(id);
        tx.commit();
        return episode;
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
        return null;
    } finally {
        session.close();
    }
}

From source file:com.caa.koko.auth.CalNetUserDetailService.java

License:Apache License

private User lookupCalNetUID(int uid) throws NamingException {
    log.debug("Querying info for CalNet UID: {}", uid);

    Session s = sessionFactory.openSession();
    Object u = s.byId(User.class).load(uid);

    if (u == null) {
        log.debug("No existing user for '{}' found; querying LDAP.", uid);

        DirContextAdapter a = (DirContextAdapter) ldapTemplate.lookup("uid=" + uid + ",ou=people");

        String name = (String) a.getAttributes().get("displayName").get();
        String email = "fake@berkeley.edu"; // TODO
        String phone = "0000000000"; // TODO

        User user = new User(uid);
        user.setEmail(email);/*  w w  w.j  a v  a 2  s .c  o m*/
        user.setName(name);
        user.setPhone(phone);

        s.save(user);
        s.flush();
        s.close();

        return user;
    } else {
        log.debug("Mapped {} => '{}'.", uid, ((User) u).getName());

        s.close();
        return (User) u;
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

License:Apache License

/**
 * modify/*  w w  w  .j  a v  a  2s. co  m*/
 */
public <T extends ObjectType> RObject<T> modifyObject(Class<T> type, String oid,
        Collection<? extends ItemDelta> modifications, PrismObject<T> prismObject, Session session)
        throws SchemaException {

    LOGGER.trace("Starting to build entity changes for {}, {}, \n{}", type, oid,
            DebugUtil.debugDumpLazily(modifications));

    // normalize reference.relation qnames like it's done here ObjectTypeUtil.normalizeAllRelations(prismObject);

    // how to generate identifiers correctly now? to repo entities and to full xml, ids in full XML are generated
    // on different place than we later create new containers...how to match them

    // set proper owner/ownerOid/ownerType for containers/references/result and others

    // todo implement transformation from prism to entity (PrismEntityMapper), probably ROperationResult missing

    // validate lookup tables and certification campaigns

    // mark newly added containers/references as transient

    // validate metadata/*, assignment/metadata/*, assignment/construction/resourceRef changes

    PrismIdentifierGenerator<T> idGenerator = new PrismIdentifierGenerator<>(
            PrismIdentifierGenerator.Operation.MODIFY);
    idGenerator.collectUsedIds(prismObject);

    // preprocess modifications
    Collection<? extends ItemDelta> processedModifications = prismObject
            .narrowModifications((Collection<? extends ItemDelta<?, ?>>) modifications);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Narrowed modifications:\n{}", DebugUtil.debugDumpLazily(modifications));
    }

    // process only real modifications
    Class<? extends RObject> objectClass = RObjectType.getByJaxbType(type).getClazz();
    RObject<T> object = session.byId(objectClass).getReference(oid);

    ManagedType mainEntityType = entityRegistry.getJaxbMapping(type);

    boolean modifiesShadowPendingOperation = false;

    for (ItemDelta delta : processedModifications) {
        ItemPath path = delta.getPath();

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Processing delta with path '{}'", path);
        }

        if (isObjectExtensionDelta(path) || isShadowAttributesDelta(path)) {
            if (delta.getPath().size() == 1) {
                handleObjectExtensionWholeContainer(object, delta, idGenerator);
            } else {
                handleObjectExtensionOrAttributesDelta(object, delta, idGenerator);
            }

            continue;
        }

        AttributeStep attributeStep = new AttributeStep();
        attributeStep.managedType = mainEntityType;
        attributeStep.bean = object;

        Iterator<?> segments = path.getSegments().iterator();
        while (segments.hasNext()) {
            Object segment = segments.next();
            if (!ItemPath.isName(segment)) {
                throw new SystemException("Segment '" + segment + "' in '" + path + "' is not a name item");
            }

            ItemName name = ItemPath.toName(segment);
            String nameLocalPart = name.getLocalPart();

            if (isAssignmentExtensionDelta(attributeStep, name)) {
                ItemName lastName = delta.getPath().lastName();
                if (AssignmentType.F_EXTENSION.equals(lastName)) {
                    handleAssignmentExtensionWholeContainer((RAssignment) attributeStep.bean, delta,
                            idGenerator);
                } else {
                    handleAssignmentExtensionDelta((RAssignment) attributeStep.bean, delta, idGenerator);
                }
                continue;
            }

            if (isOperationResult(delta)) {
                handleOperationResult(attributeStep.bean, delta);
                continue;
            }

            if (isMetadata(delta)) {
                handleMetadata(attributeStep.bean, delta);
            }

            if (isFocusPhoto(delta)) {
                handlePhoto(attributeStep.bean, delta);
                continue;
            }

            if (isShadowPendingOperation(object, delta)) {
                modifiesShadowPendingOperation = true;
            }

            Attribute attribute = findAttribute(attributeStep, nameLocalPart, path, segments, name);
            if (attribute == null) {
                // there's no table/column that needs update
                break;
            }

            if (segments.hasNext()) {
                attributeStep = stepThroughAttribute(attribute, attributeStep, segments);

                continue;
            }

            handleAttribute(attribute, attributeStep.bean, delta, prismObject, idGenerator);

            if ("name".equals(attribute.getName())
                    && RObject.class.isAssignableFrom(attribute.getDeclaringType().getJavaType())) {
                // we also need to handle "nameCopy" column, we doesn't need path/segments/nameSegment for this call
                Attribute nameCopyAttribute = findAttribute(attributeStep, "nameCopy", null, null, null);
                handleAttribute(nameCopyAttribute, attributeStep.bean, delta, prismObject, idGenerator);
            }
        }
    }

    // the following will apply deltas to prismObject
    handleObjectCommonAttributes(type, processedModifications, prismObject, object, idGenerator);

    if (modifiesShadowPendingOperation) {
        handleShadowPendingOperation(object, prismObject);
    }

    LOGGER.trace("Entity changes applied");

    return object;
}

From source file:controller.CompanyDAOImpl.java

@Override
public Company getCompanyById(long id) {
    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction t = s.beginTransaction();
    Company e = (Company) s.byId(Company.class).load(id);
    t.commit();/*from w w  w .  j a  v  a 2  s .c o m*/
    s.close();
    return e;
}

From source file:controller.DepartmentDAOImpl.java

@Override
public Department getDepartmentById(long id) {
    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction t = s.beginTransaction();
    Department d = (Department) s.byId(Department.class).load(id);
    ;// w  w  w.  j  a v a  2 s .  c  om
    t.commit();
    s.close();
    return d;
}

From source file:controller.EmployeeDAOImpl.java

@Override
public Employee getEmployeeById(long id) {
    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction t = s.beginTransaction();
    Employee e = (Employee) s.byId(Employee.class).load(id);
    t.commit();//from ww w.  j  a  v a 2  s  .c  o  m
    s.close();
    return e;
}

From source file:org.musicrecital.dao.hibernate.GenericDaoHibernate.java

License:Apache License

/**
 * {@inheritDoc}/* www  .j a  va  2 s  .c  om*/
 */
@SuppressWarnings("unchecked")
public T get(PK id) {
    Session sess = getSession();
    IdentifierLoadAccess byId = sess.byId(persistentClass);
    T entity = (T) byId.load(id);

    if (entity == null) {
        log.warn("Uh oh, '" + this.persistentClass + "' object with id '" + id + "' not found...");
        throw new ObjectRetrievalFailureException(this.persistentClass, id);
    }

    return entity;
}

From source file:org.musicrecital.dao.hibernate.GenericDaoHibernate.java

License:Apache License

/**
 * {@inheritDoc}//w ww .jav a  2  s .  c  o  m
 */
@SuppressWarnings("unchecked")
public boolean exists(PK id) {
    Session sess = getSession();
    IdentifierLoadAccess byId = sess.byId(persistentClass);
    T entity = (T) byId.load(id);
    return entity != null;
}

From source file:org.musicrecital.dao.hibernate.GenericDaoHibernate.java

License:Apache License

/**
 * {@inheritDoc}// w  w  w.jav  a2  s .  c  o  m
 */
public void remove(PK id) {
    Session sess = getSession();
    IdentifierLoadAccess byId = sess.byId(persistentClass);
    T entity = (T) byId.load(id);
    sess.delete(entity);
}

From source file:org.yamj.core.database.dao.ConfigDao.java

License:Open Source License

public void storeConfig(String key, String value, boolean updateAllowed) {
    Session session = currentSession();
    Configuration config = (Configuration) session.byId(Configuration.class).load(key);
    if (config == null) {
        LOG.debug("Store new configuration: key='{}', value='{}'", key, value);
        config = new Configuration();
        config.setKey(key);//from  w  w w .  j av a 2 s.  com
        config.setValue(value);
        session.save(config);
    } else if (updateAllowed) {
        config.setValue(value);
        session.update(config);
    }
}