Search in sources :

Example 1 with ParamNode

use of org.webpieces.router.impl.params.ParamNode in project webpieces by deanhiller.

the class HibernateLookup method find.

@SuppressWarnings("unchecked")
@Override
public <T> T find(Meta paramMeta, ParamTreeNode tree, Function<Class<T>, T> beanCreate) {
    if (!(paramMeta instanceof ParamMeta))
        throw new UnsupportedOperationException("this plugin does not support type=" + paramMeta.getClass());
    ParamMeta m = (ParamMeta) paramMeta;
    Class<T> paramTypeToCreate = (Class<T>) m.getFieldClass();
    EntityManager entityManager = Em.get();
    Metamodel metamodel = entityManager.getMetamodel();
    ManagedType<T> managedType = metamodel.managedType(paramTypeToCreate);
    EntityTypeImpl<T> entityType = (EntityTypeImpl<T>) managedType;
    Class<?> idClazz = entityType.getIdType().getJavaType();
    SingularAttribute<? super T, ?> idAttribute = entityType.getId(idClazz);
    String name = idAttribute.getName();
    ParamNode paramNode = tree.get(name);
    String value = null;
    if (paramNode != null) {
        if (!(paramNode instanceof ValueNode))
            throw new IllegalStateException("The id field in the hibernate entity should have matched to a " + "ValueNode on incoming data and did not. node=" + paramNode + ".  bad multipart form?  (Please " + "let us know so we can pair with you on this and I can add better error messaging)");
        ValueNode node = (ValueNode) paramNode;
        value = node.getValue();
    }
    if (value == null)
        return beanCreate.apply(paramTypeToCreate);
    @SuppressWarnings("rawtypes") ObjectStringConverter unmarshaller = translator.getConverter(idClazz);
    Object id = unmarshaller.stringToObject(value);
    UseQuery namedQuery = fetchUseQuery(m.getAnnotations());
    if (namedQuery == null)
        return entityManager.find(paramTypeToCreate, id);
    Query query = entityManager.createNamedQuery(namedQuery.value());
    query.setParameter(namedQuery.id(), id);
    return (T) query.getSingleResult();
}
Also used : Query(javax.persistence.Query) ParamNode(org.webpieces.router.impl.params.ParamNode) EntityManager(javax.persistence.EntityManager) ParamMeta(org.webpieces.router.impl.params.ParamMeta) EntityTypeImpl(org.hibernate.metamodel.internal.EntityTypeImpl) ValueNode(org.webpieces.router.impl.params.ValueNode) Metamodel(javax.persistence.metamodel.Metamodel) ObjectStringConverter(org.webpieces.router.api.ObjectStringConverter)

Aggregations

EntityManager (javax.persistence.EntityManager)1 Query (javax.persistence.Query)1 Metamodel (javax.persistence.metamodel.Metamodel)1 EntityTypeImpl (org.hibernate.metamodel.internal.EntityTypeImpl)1 ObjectStringConverter (org.webpieces.router.api.ObjectStringConverter)1 ParamMeta (org.webpieces.router.impl.params.ParamMeta)1 ParamNode (org.webpieces.router.impl.params.ParamNode)1 ValueNode (org.webpieces.router.impl.params.ValueNode)1