@Override public Method load(final PluralAttribute<?, ?, ?> attribute) { final Class<?> declaringClass = attribute.getDeclaringType().getJavaType(); final String getterName = getGetterName(attribute); final Method readMethod = BeanUtils.findDeclaredMethod(declaringClass, getterName); if (readMethod == null) { throw new IllegalStateException(String.format( "Class %s does not declare method named '%s'", declaringClass.getName(), getterName)); } readMethod.setAccessible(true); return readMethod; }
@Nonnull static <T, U, C extends Collection<U>> Function<T, C> jpaCollection( @Nonnull final PluralAttribute<? super T, C, U> attribute) { Objects.requireNonNull(attribute); final Class<C> collectionType = attribute.getJavaType(); try { final Method readMethod = ENTITY_COLLECTION_GETTERS.get(attribute); return obj -> invokeAndCast(readMethod, obj, collectionType); } catch (final ExecutionException e) { throw new RuntimeException(e); } }
public static <T, U, C extends Collection<U>> void updateInverseCollection( @Nonnull final PluralAttribute<? super T, C, U> inverseAttribute, @Nonnull final U entity, @Nullable final T currentAssociation, @Nullable final T newAssociation) { Objects.requireNonNull(inverseAttribute, "inverseAttribute is null"); Objects.requireNonNull(entity, "entity is null"); final Function<T, C> fn = getCollectionIfInitialized(inverseAttribute); final C oldCollection = fn.apply(currentAssociation); if (oldCollection != null) { oldCollection.remove(entity); } final C newCollection = fn.apply(newAssociation); if (newCollection != null) { newCollection.add(entity); } }
@SuppressWarnings("unchecked") @Nonnull public static <T, U> Join<T, U> join( @Nonnull final From<?, T> from, @Nonnull final PluralAttribute<? super T, ?, U> attribute) { Objects.requireNonNull(from, "from is null"); Objects.requireNonNull(attribute, "attribute is null"); if (attribute instanceof CollectionAttribute) { return from.join((CollectionAttribute<T, U>) attribute); } if (attribute instanceof SetAttribute) { return from.join((SetAttribute<T, U>) attribute); } if (attribute instanceof ListAttribute) { return from.join((ListAttribute<T, U>) attribute); } if (attribute instanceof MapAttribute) { return from.join((MapAttribute<T, ?, U>) attribute); } // Should never end up here. throw new IllegalArgumentException(); }
@Bean public CacheManager cacheManager(JHipsterProperties jHipsterProperties) { log.debug("Starting Ehcache"); cacheManager = net.sf.ehcache.CacheManager.create(); cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap()); log.debug("Registering Ehcache Metrics gauges"); Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities(); for (EntityType<?> entity : entities) { String name = entity.getName(); if (name == null || entity.getJavaType() != null) { name = entity.getJavaType().getName(); } Assert.notNull(name, "entity cannot exist without an identifier"); reconfigureCache(name, jHipsterProperties); for (PluralAttribute pluralAttribute : entity.getPluralAttributes()) { reconfigureCache(name + "." + pluralAttribute.getName(), jHipsterProperties); } } EhCacheCacheManager ehCacheManager = new EhCacheCacheManager(); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }
public Attribute<?, ?> filter() { Type<?> type = forModel(metamodel).filter(rootType); Attribute<?, ?> result = null; for (int i = 1; i < pathElements.length; i++) { if (!(type instanceof ManagedType)) { throw new PersistenceException("Cannot navigate through simple property " + pathElements[i] + " of type " + type.getJavaType()); } result = ((ManagedType<?>)type).getAttribute(pathElements[i]); if (result.isCollection()) { type = ((PluralAttribute<?, ?, ?>)result).getElementType(); } else { type = ((SingularAttribute<?, ?>)result).getType(); } } return result; }
public boolean visitJoin(Node node, Set<TypeDefinition> typeDefinitions) { if (node.jjtGetNumChildren() != 2) { return false; } Node pathNode = node.jjtGetChild(0); Node aliasNode = node.jjtGetChild(1); Alias rootAlias = new Alias(pathNode.jjtGetChild(0).toString()); Class<?> rootType = getType(rootAlias, typeDefinitions); ManagedType<?> managedType = forModel(metamodel).filter(rootType); for (int i = 1; i < pathNode.jjtGetNumChildren(); i++) { Attribute<?, ?> attribute = managedType.getAttribute(pathNode.jjtGetChild(i).toString()); if (attribute.getPersistentAttributeType() == PersistentAttributeType.BASIC) { throw new PersistenceException("Cannot navigate through basic property " + pathNode.jjtGetChild(i) + " of path " + pathNode); } if (attribute.isCollection()) { PluralAttribute<?, ?, ?> pluralAttribute = (PluralAttribute<?, ?, ?>)attribute; managedType = (ManagedType<?>)pluralAttribute.getElementType(); } else { managedType = (ManagedType<?>)((SingularAttribute)attribute).getType(); } } typeDefinitions.add(new TypeDefinition(new Alias(aliasNode.toString()), managedType.getJavaType())); return false; }
public static Type toType(Bindable bindable) { switch ( bindable.getBindableType() ) { case ENTITY_TYPE: { return (EntityType) bindable; } case SINGULAR_ATTRIBUTE: { return ( (SingularAttribute) bindable ).getType(); } case PLURAL_ATTRIBUTE: { return ( (PluralAttribute) bindable ).getElementType(); } default: { throw new ParsingException( "Unexpected Bindable type : " + bindable ); } } }
@Override public <Y> JpaFetch<X, Y> fetch(PluralAttribute<? super X, ?, Y> pluralAttribute, JoinType jt) { // if ( !canBeFetchSource() ) { // throw illegalFetch(); // } // // final Fetch<X, Y> fetch; // // TODO : combine Fetch and Join hierarchies (JoinImplementor extends Join,Fetch???) // if ( PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) { // fetch = constructJoin( (CollectionAttribute<X, Y>) pluralAttribute, jt ); // } // else if ( PluralAttribute.CollectionType.LIST.equals( pluralAttribute.getCollectionType() ) ) { // fetch = constructJoin( (ListAttribute<X, Y>) pluralAttribute, jt ); // } // else if ( PluralAttribute.CollectionType.SET.equals( pluralAttribute.getCollectionType() ) ) { // fetch = constructJoin( (SetAttribute<X, Y>) pluralAttribute, jt ); // } // else { // fetch = constructJoin( (MapAttribute<X, ?, Y>) pluralAttribute, jt ); // } // joinScope.addFetch( fetch ); // return fetch; throw new NotYetImplementedException( ); }
@Override @SuppressWarnings({ "unchecked" }) public <E, C extends Collection<E>> JpaExpression<C> get(PluralAttribute<X, C, E> attribute) { // if ( ! canBeDereferenced() ) { // throw illegalDereference(); // } // // PluralAttributePath<C> path = (PluralAttributePath<C>) resolveCachedAttributePath( attribute.getName() ); // if ( path == null ) { // path = new PluralAttributePath<C>( criteriaBuilder(), this, attribute ); // registerAttributePath( attribute.getName(), path ); // } // return path; throw new NotYetImplementedException( ); }
@SuppressWarnings("unchecked") public <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) { Path<?> path = root; for (Attribute<?, ?> attribute : attributes) { boolean found = false; if (path instanceof FetchParent) { for (Fetch<E, ?> fetch : ((FetchParent<?, E>) path).getFetches()) { if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) { path = (Join<E, ?>) fetch; found = true; break; } } } if (!found) { if (attribute instanceof PluralAttribute) { path = ((From<?, ?>) path).join(attribute.getName(), JoinType.LEFT); } else { path = path.get(attribute.getName()); } } } return (Path<F>) path; }
public void verifyPath(List<Attribute<?, ?>> path) { List<Attribute<?, ?>> attributes = newArrayList(path); Class<?> from = null; if (attributes.get(0).isCollection()) { from = ((PluralAttribute) attributes.get(0)).getElementType().getJavaType(); } else { from = attributes.get(0).getJavaType(); } attributes.remove(0); for (Attribute<?, ?> attribute : attributes) { if (!attribute.getDeclaringType().getJavaType().isAssignableFrom(from)) { throw new IllegalStateException("Wrong path."); } from = attribute.getJavaType(); } }
@SuppressWarnings({"unchecked", "rawtypes"}) protected void fetches(SearchParameters sp, Root<E> root) { for (List<Attribute<?, ?>> args : sp.getFetches()) { FetchParent<?, ?> from = root; for (Attribute<?, ?> arg : args) { boolean found = false; for (Fetch<?, ?> fetch : from.getFetches()) { if (arg.equals(fetch.getAttribute())) { from = fetch; found = true; break; } } if (!found) { if (arg instanceof PluralAttribute) { from = from.fetch((PluralAttribute) arg, JoinType.LEFT); } else { from = from.fetch((SingularAttribute) arg, JoinType.LEFT); } } } } }
public List<Attribute<?, ?>> toAttributes(String path, Class<?> from) { try { List<Attribute<?, ?>> attributes = newArrayList(); Class<?> current = from; for (String pathItem : Splitter.on(".").split(path)) { Class<?> metamodelClass = getCachedClass(current); Field field = metamodelClass.getField(pathItem); Attribute<?, ?> attribute = (Attribute<?, ?>) field.get(null); attributes.add(attribute); if (attribute instanceof PluralAttribute) { current = ((PluralAttribute<?, ?, ?>) attribute).getElementType().getJavaType(); } else { current = attribute.getJavaType(); } } return attributes; } catch (Exception e) { throw new IllegalArgumentException(e); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) public <E> void fetches(SearchParameters<E> sp, Root<E> root) { for (jpasearch.repository.query.Path<E, ?> path : sp.getFetches()) { FetchParent<?, ?> from = root; for (Attribute<?, ?> arg : metamodelUtil.toAttributes(root.getJavaType(), path.getPath())) { boolean found = false; for (Fetch<?, ?> fetch : from.getFetches()) { if (arg.equals(fetch.getAttribute())) { from = fetch; found = true; break; } } if (!found) { if (arg instanceof PluralAttribute) { from = from.fetch((PluralAttribute) arg, JoinType.LEFT); } else { from = from.fetch((SingularAttribute) arg, JoinType.LEFT); } } } } }
public List<Attribute<?, ?>> toAttributes(Class<?> from, String path) { try { List<Attribute<?, ?>> attributes = new ArrayList<>(); Class<?> current = from; for (String pathItem : Splitter.on(".").split(path)) { Class<?> metamodelClass = metamodelCache.get(current); Field field = metamodelClass.getField(pathItem); Attribute<?, ?> attribute = (Attribute<?, ?>) field.get(null); attributes.add(attribute); if (attribute instanceof PluralAttribute) { current = ((PluralAttribute<?, ?, ?>) attribute).getElementType().getJavaType(); } else { current = attribute.getJavaType(); } } return attributes; } catch (Exception e) { throw new IllegalArgumentException(e); } }
/** * This clumsy code is just to get the class of plural attribute mapping * * @param et * @param fieldName * @return */ private Class<?> getPluralJavaType(EntityType<?> et, String fieldName) { for (PluralAttribute pa : et.getPluralAttributes()) { if (pa.getName().equals(fieldName)) { switch (pa.getCollectionType()) { case COLLECTION: return et.getCollection(fieldName).getElementType().getJavaType(); case LIST: return et.getList(fieldName).getElementType().getJavaType(); case SET: return et.getSet(fieldName).getElementType().getJavaType(); case MAP: throw new UnsupportedOperationException("Entity Map mapping unsupported for entity: " + et.getName() + " field name: " + fieldName); } } } throw new IllegalArgumentException("Field " + fieldName + " of entity " + et.getName() + " is not a plural attribute"); }
@Test public void hibernatePluralPathTest() { CriteriaBuilder build = em.getCriteriaBuilder(); CriteriaQuery<OneToManyInstance> critQ = build.createQuery(OneToManyInstance.class); Root<OneToManyInstance> resultRoot = critQ.from(OneToManyInstance.class); Path pluralPath = resultRoot.get("many"); Bindable shouldBePluralAttribute = pluralPath.getModel(); assertNotNull(shouldBePluralAttribute); assertTrue(shouldBePluralAttribute instanceof PluralAttribute); }
@Nonnull public static <P, S> JpaSubQuery<P, S> of(@Nonnull final PluralAttribute<P, ?, S> attribute) { return new AbstractSubQuery<P, S, PluralAttribute<P, ?, S>>(Objects.requireNonNull(attribute)) { @Override protected From<P, S> join(final Root<P> root) { return CriteriaUtils.join(root, attribute); } }; }
@Nonnull public static <P, S> JpaSubQuery<P, S> inverseOf(@Nonnull final PluralAttribute<S, ?, P> attribute) { return new AbstractReverseSubQuery<P, S, PluralAttribute<S, ?, P>>(Objects.requireNonNull(attribute)) { @Override protected Path<P> getPathToParentRoot(final Root<S> root) { return CriteriaUtils.join(root, attribute); } }; }
public static <T, U> boolean isCollectionLoaded( @Nonnull final T entity, @Nonnull final PluralAttribute<? super T, ? extends Collection<U>, U> pluralAttribute) { Objects.requireNonNull(entity, "entity is null"); return getCollectionIfInitialized(pluralAttribute).apply(entity) != null; }
private static <T, U, C extends Collection<U>> Function<T, C> getCollectionIfInitialized( final PluralAttribute<? super T, C, U> attribute) { Objects.requireNonNull(attribute); return new Function<T, C>() { // Cache for lazy-initialized function, not strictly thread-safe private Function<T, C> collectionFn; @Nullable @Override public C apply(@Nullable final T entity) { if (entity == null || !Hibernate.isInitialized(entity)) { return null; } if (collectionFn == null) { collectionFn = jpaCollection(attribute); } final C collection = collectionFn.apply(entity); return Hibernate.isInitialized(collection) ? collection : null; } }; }
@Nonnull public static <T, X, Y> Specification<T> equal( @Nonnull final PluralAttribute<? super T, ?, X> attribute1, @Nonnull final SingularAttribute<? super X, Y> attribute2, @Nullable final Y value) { Objects.requireNonNull(attribute1, "attribute1 must not be null"); Objects.requireNonNull(attribute2, "attribute2 must not be null"); return (root, query, cb) -> JpaPreds.equal(cb, CriteriaUtils.join(root, attribute1).get(attribute2), value); }
@Override protected ManagedType<?> transform(TypeDefinition typeDefinition) { if (!path.hasSubpath()) { return forModel(metamodel).filter(typeDefinition.getType()); } Attribute<?, ?> attribute = (Attribute<?, ?>)filter.transform(typeDefinition); if (attribute.isCollection()) { return (ManagedType<?>)((PluralAttribute<?, ?, ?>)attribute).getElementType(); } else { return (ManagedType<?>)((SingularAttribute<?, ?>)attribute).getType(); } }
/** * Gets a collection's metadata from the property descriptor. * * @param collections The list of plural attributes to process. * @return The list of collections for this data object. */ protected List<DataObjectCollection> getCollectionsFromMetadata(Set<PluralAttribute> collections) { List<DataObjectCollection> colls = new ArrayList<DataObjectCollection>(collections.size()); for (PluralAttribute cd : collections) { colls.add(getCollectionMetadataFromCollectionAttribute(cd)); } return colls; }
public static Class<?> getAttributeClass(final Attribute<?, ?> attribute) { if (attribute == null) { throw new NullPointerException(ATTRIBUTE_CANNOT_BE_NULL); } if (attribute instanceof PluralAttribute) { return ((PluralAttribute) attribute).getBindableJavaType(); } return attribute.getJavaType(); }
@Override @SuppressWarnings({"unchecked"}) public <X, Y> JpaAttributeJoin<X, Y> join(String attributeName, JoinType jt) { if ( !canBeJoinSource() ) { throw illegalJoin(); } if ( jt.equals( JoinType.RIGHT ) ) { throw new UnsupportedOperationException( "RIGHT JOIN not supported" ); } final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute( attributeName ); if ( attribute.isCollection() ) { final PluralAttribute pluralAttribute = (PluralAttribute) attribute; if ( PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) { return (JpaAttributeJoin<X, Y>) join( (CollectionAttribute) attribute, jt ); } else if ( PluralAttribute.CollectionType.LIST.equals( pluralAttribute.getCollectionType() ) ) { return (JpaAttributeJoin<X, Y>) join( (ListAttribute) attribute, jt ); } else if ( PluralAttribute.CollectionType.SET.equals( pluralAttribute.getCollectionType() ) ) { return (JpaAttributeJoin<X, Y>) join( (SetAttribute) attribute, jt ); } else { return (JpaAttributeJoin<X, Y>) join( (MapAttribute) attribute, jt ); } } else { return (JpaAttributeJoin<X, Y>) join( (SingularAttribute) attribute, jt ); } }
@Override @SuppressWarnings({"unchecked"}) public <X, Y> JpaCollectionJoin<X, Y> joinCollection(String attributeName, JoinType jt) { final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute( attributeName ); if ( !attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a collection" ); } final PluralAttribute pluralAttribute = (PluralAttribute) attribute; if ( !PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a collection" ); } return (JpaCollectionJoin<X, Y>) join( (CollectionAttribute) attribute, jt ); }
@Override @SuppressWarnings({"unchecked"}) public <X, Y> JpaSetJoin<X, Y> joinSet(String attributeName, JoinType jt) { final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute( attributeName ); if ( !attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a set" ); } final PluralAttribute pluralAttribute = (PluralAttribute) attribute; if ( !PluralAttribute.CollectionType.SET.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a set" ); } return (JpaSetJoin<X, Y>) join( (SetAttribute) attribute, jt ); }
@Override @SuppressWarnings({"unchecked"}) public <X, Y> JpaListJoin<X, Y> joinList(String attributeName, JoinType jt) { final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute( attributeName ); if ( !attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a list" ); } final PluralAttribute pluralAttribute = (PluralAttribute) attribute; if ( !PluralAttribute.CollectionType.LIST.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a list" ); } return (JpaListJoin<X, Y>) join( (ListAttribute) attribute, jt ); }
@Override @SuppressWarnings({"unchecked"}) public <X, K, V> JpaMapJoin<X, K, V> joinMap(String attributeName, JoinType jt) { final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute( attributeName ); if ( !attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a map" ); } final PluralAttribute pluralAttribute = (PluralAttribute) attribute; if ( !PluralAttribute.CollectionType.MAP.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a map" ); } return (JpaMapJoin<X, K, V>) join( (MapAttribute) attribute, jt ); }
@Override @SuppressWarnings({"unchecked"}) public <X, Y> JpaFetch<X, Y> fetch(String attributeName, JoinType jt) { if ( !canBeFetchSource() ) { throw illegalFetch(); } Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute( attributeName ); if ( attribute.isCollection() ) { return (JpaFetch<X, Y>) fetch( (PluralAttribute) attribute, jt ); } else { return (JpaFetch<X, Y>) fetch( (SingularAttribute) attribute, jt ); } }
private Predicate getPredicate(CriteriaBuilder cb, Root root, DataFetchingEnvironment environment, Argument argument) { Path path = null; if (!argument.getName().contains(".")) { Attribute argumentEntityAttribute = getAttribute(environment, argument); // If the argument is a list, let's assume we need to join and do an 'in' clause if (argumentEntityAttribute instanceof PluralAttribute) { Join join = root.join(argument.getName()); return join.in(convertValue(environment, argument, argument.getValue())); } path = root.get(argument.getName()); return cb.equal(path, convertValue(environment, argument, argument.getValue())); } else { List<String> parts = Arrays.asList(argument.getName().split("\\.")); for (String part : parts) { if (path == null) { path = root.get(part); } else { path = path.get(part); } } return cb.equal(path, convertValue(environment, argument, argument.getValue())); } }
private Class getJavaType(DataFetchingEnvironment environment, Argument argument) { Attribute argumentEntityAttribute = getAttribute(environment, argument); if (argumentEntityAttribute instanceof PluralAttribute) return ((PluralAttribute) argumentEntityAttribute).getElementType().getJavaType(); return argumentEntityAttribute.getJavaType(); }
private void addForeignKeys(MetadataFactory mf, Metamodel model, ManagedType<?> entity, Table entityTable) throws TranslatorException { for (Attribute<?, ?> attr:entity.getAttributes()) { if (attr.isCollection()) { PluralAttribute pa = (PluralAttribute)attr; Table forignTable = null; for (EntityType et:model.getEntities()) { if (et.getJavaType().equals(pa.getElementType().getJavaType())) { forignTable = mf.getSchema().getTable(et.getName()); break; } } if (forignTable == null) { continue; } // add foreign keys as columns in table first; check if they exist first ArrayList<String> keys = new ArrayList<String>(); KeyRecord pk = entityTable.getPrimaryKey(); for (Column entityColumn:pk.getColumns()) { addColumn(mf, entityColumn.getName(), entityColumn.getDatatype().getRuntimeTypeName(), forignTable); keys.add(entityColumn.getName()); } if (!foreignKeyExists(keys, forignTable)) { addForiegnKey(mf, attr.getName(), keys, entityTable.getName(), forignTable); } } } }
/** * Retrieves cascade from metamodel attribute * * @param attribute given pluaral attribute * @return an empty collection if no jpa relation annotation can be found. */ public Collection<CascadeType> getCascades(PluralAttribute<?, ?, ?> attribute) { if (attribute.getJavaMember() instanceof AccessibleObject) { AccessibleObject accessibleObject = (AccessibleObject) attribute.getJavaMember(); OneToMany oneToMany = accessibleObject.getAnnotation(OneToMany.class); if (oneToMany != null) { return newArrayList(oneToMany.cascade()); } ManyToMany manyToMany = accessibleObject.getAnnotation(ManyToMany.class); if (manyToMany != null) { return newArrayList(manyToMany.cascade()); } } return newArrayList(); }
public boolean isOrphanRemoval(PluralAttribute<?, ?, ?> attribute) { if (attribute.getJavaMember() instanceof AccessibleObject) { AccessibleObject accessibleObject = (AccessibleObject) attribute.getJavaMember(); OneToMany oneToMany = accessibleObject.getAnnotation(OneToMany.class); if (oneToMany != null) { return oneToMany.orphanRemoval(); } } return true; }
/** * Retrieves cascade from metamodel attribute * * @return an empty collection if no jpa relation annotation can be found. */ public Collection<CascadeType> getCascades(PluralAttribute<?, ?, ?> attribute) { if (attribute.getJavaMember() instanceof AccessibleObject) { AccessibleObject accessibleObject = (AccessibleObject) attribute.getJavaMember(); OneToMany oneToMany = accessibleObject.getAnnotation(OneToMany.class); if (oneToMany != null) { return Arrays.asList(oneToMany.cascade()); } ManyToMany manyToMany = accessibleObject.getAnnotation(ManyToMany.class); if (manyToMany != null) { return Arrays.asList(manyToMany.cascade()); } } return new ArrayList<>(); }