use of org.webpieces.router.impl.params.ParamMeta 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();
}
Aggregations