SingularAttribute<?, ?> id = root.getModel().getId(root.getModel().getIdType().getJavaType()); query = query.multiselect(root.get((SingularAttribute) id).alias(id.getName()));
private SingularAttribute<?, ?> getIdentifierAttribute(final Class<?> entityClass) { if (!idAttibuteCache.containsKey(entityClass)) { final EntityType<?> type = getEntityType(entityClass); // patch for openjpa because it returns null instead of IllegalArgumentException // when class is not an entity. Assert.notNull(type, "Not an entity: " + entityClass); idAttibuteCache.put(entityClass, type.getId(type.getIdType().getJavaType())); } return idAttibuteCache.get(entityClass); }
private TypedQuery<Long> getCountQuery(DataFetchingEnvironment environment, Field field) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<?> root = query.from(entityType); SingularAttribute<?,?> idAttribute = entityType.getId(Object.class); query.select(cb.count(root.get(idAttribute.getName()))); List<Predicate> predicates = field.getArguments().stream() .map(it -> getPredicate(cb, root, null, environment, it)) .filter(it -> it != null) .collect(Collectors.toList()); query.where(predicates.toArray(new Predicate[predicates.size()])); return entityManager.createQuery(query); }
protected <X>Attribute<? super X, ?> idAttribute(final Class<X> klazz) { final EntityType<X> type = em.getMetamodel().entity(klazz); final Class<?> idType = type.getIdType().getJavaType(); final Attribute<? super X, ?> attribute = type.getId(idType); return attribute; }
@Override public List<String> getIdentifierOrUniqueKeyEmbeddedPropertyNames(EntityType<?> ownerType, String attributeName) { Attribute<?, ?> attribute = getAttribute(ownerType, attributeName); if (((SingularAttribute<?, ?>) attribute).getType() instanceof EntityType<?>) { EntityType<?> entityType = (EntityType<?>) ((SingularAttribute<?, ?>) attribute).getType(); if (entityType.hasSingleIdAttribute()) { return Collections.singletonList(entityType.getId(entityType.getIdType().getJavaType()).getName()); } else { Set<SingularAttribute<?, ?>> attributes = (Set<SingularAttribute<?, ?>>) (Set) entityType.getIdClassAttributes(); List<String> attributeNames = new ArrayList<>(attributes.size()); for (Attribute<?, ?> attr : attributes) { attributeNames.add(attr.getName()); } return attributeNames; } } return Collections.emptyList(); }
@Override @SuppressWarnings("unchecked") public Predicate convert(IdentitySpecification<A, I> specification, JpaTranslationContext<A> context, SpecificationTranslator<JpaTranslationContext<A>, Predicate> translator) { I expectedIdentifier = specification.getExpectedIdentifier(); Root<A> root = context.getRoot(); return context.getCriteriaBuilder().equal( root.get(root.getModel().getId((Class<I>) expectedIdentifier.getClass())), expectedIdentifier ); } }
/** * Sets the ID of the given object, which must be a JPA entity, to its default * value. The default value for reference types is {@code null}; the default * value for primitive types is the same as the JVM default value for an * uninitialized field. * * @param entity * the JPA entity whose ID value to clear */ private <X> void clearId(X entity) { // XXX probably need to pass in the actual entity class rather than this cast // (because dynamic proxies will fool it) @SuppressWarnings("unchecked") EntityType<X> type = em.getMetamodel().entity((Class<X>) entity.getClass()); SingularAttribute<? super X, ?> attr = type.getId(type.getIdType().getJavaType()); attributeAccessor.set(attr, entity, null); }
/** * Returns count of all foreign key references to entity of given entity type with given ID of given identifier type. * This is particularly useful in case you intend to check if the given entity is still referenced elsewhere in database. * @param <T> The generic result type. * @param <I> The generic identifier type. * @param entityManager The involved entity manager. * @param entityType Entity type. * @param identifierType Identifier type. * @param id Entity ID. * @return Count of all foreign key references to entity of given entity type with given ID of given identifier type. */ public static <T, I> long countForeignKeyReferences(EntityManager entityManager, Class<T> entityType, Class<I> identifierType, I id) { Metamodel metamodel = entityManager.getMetamodel(); SingularAttribute<? super T, I> idAttribute = metamodel.entity(entityType).getId(identifierType); return metamodel.getEntities().stream() .flatMap(entity -> getAttributesOfType(entity, entityType)) .distinct() .mapToLong(attribute -> countReferencesTo(entityManager, attribute, idAttribute, id)) .sum(); }
/** * Returns the ID of the given object, which must be a JPA entity. * * @param entity * the JPA entity whose ID value to retrieve * @return The ID of the given entity. If the entity ID type is primitive (for * example, {@code int} as opposed to {@code Integer}), the * corresponding boxed value will be returned. */ private <X> Object id(X entity) { // XXX probably need to pass in the actual entity class rather than this cast // (because dynamic proxies will fool it) @SuppressWarnings("unchecked") EntityType<X> type = em.getMetamodel().entity((Class<X>) entity.getClass()); SingularAttribute<? super X, ?> attr = type.getId(type.getIdType().getJavaType()); return attributeAccessor.get(attr, entity); }
SingularAttribute parentIdAttribute = entityType.getId(Object.class);
public JpaValueEncoder(final EntityType<E> entity, final EntityManagerManager entityManagerManager, final String persistenceUnitName, final PropertyAccess propertyAccess, final TypeCoercer typeCoercer, final Logger logger) { super(); this.entity = entity; this.entityManagerManager = entityManagerManager; this.persistenceUnitName = persistenceUnitName; this.typeCoercer = typeCoercer; this.logger = logger; final Type<?> idType = this.entity.getIdType(); final SingularAttribute<? super E, ?> idAttribute = this.entity.getId(idType.getJavaType()); idPropertyName = idAttribute.getName(); propertyAdapter = propertyAccess.getAdapter(entity.getJavaType()).getPropertyAdapter( idPropertyName); }
protected final void indexSomeCompanies(int count) { EntityManager em = null; try { em = emf.createEntityManager(); em.getTransaction().begin(); CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<Company> criteria = criteriaBuilder.createQuery( Company.class ); Root<Company> root = criteria.from( Company.class ); Path<Integer> id = root.get( root.getModel().getId( int.class ) ); criteria.orderBy( criteriaBuilder.asc( id ) ); List<Company> companies = em.createQuery( criteria ).setMaxResults( count ).getResultList(); FullTextEntityManager ftEm = Search.getFullTextEntityManager( em ); companies.forEach( ftEm::index ); em.getTransaction().commit(); } finally { if ( em != null ) { em.close(); } } } }
public JpaValueEncoder(final EntityType<E> entity, final EntityManagerManager entityManagerManager, final String persistenceUnitName, final PropertyAccess propertyAccess, final TypeCoercer typeCoercer, final Logger logger) { super(); this.entity = entity; this.entityManagerManager = entityManagerManager; this.persistenceUnitName = persistenceUnitName; this.typeCoercer = typeCoercer; this.logger = logger; final Type<?> idType = this.entity.getIdType(); final SingularAttribute<? super E, ?> idAttribute = this.entity.getId(idType.getJavaType()); idPropertyName = idAttribute.getName(); propertyAdapter = propertyAccess.getAdapter(entity.getJavaType()).getPropertyAdapter( idPropertyName); }
@Override public void run() { repService.persist(bean); if (!connected) { entity = connection().getMetamodel().entity(bean.getClass()); String idName = entity.getId(bean.getClass()).getName(); id = BeanClass.getValue(bean, idName); repService.persist(new ReplicationChange(entity.getName(), id)); } }
Field sortField = getSortAnnotation(entityType.getBindableJavaType()); if (sortField == null) query.orderBy(criteriaBuilder.asc(from.get(entityType.getId(entityType.getIdType().getJavaType()).getName()))); else { GraphQLDefaultOrderBy order = sortField.getAnnotation(GraphQLDefaultOrderBy.class);
/**** utility functions ***/ static void applyOProperties(EntityManager em, ManagedType<?> jpaManagedType, Collection<OProperty<?>> properties, Object jpaEntity) { for (OProperty<?> prop : properties) { boolean found = false; if (jpaManagedType instanceof EntityType) { EntityType<?> jpaEntityType = (EntityType<?>) jpaManagedType; if (jpaEntityType.getIdType().getPersistenceType() == PersistenceType.EMBEDDABLE) { EmbeddableType<?> et = (EmbeddableType<?>) jpaEntityType .getIdType(); for (Attribute<?, ?> idAtt : et.getAttributes()) { if (idAtt.getName().equals(prop.getName())) { Object idValue = JPAMember.create( jpaEntityType.getId(et.getJavaType()), jpaEntity).get(); setAttribute(idAtt, prop, idValue); found = true; break; } } } } if (found) continue; Attribute<?, ?> att = jpaManagedType.getAttribute(prop.getName()); setAttribute(att, prop, jpaEntity); } }
static Object createNewJPAEntity( EntityManager em, EntityType<?> jpaEntityType, OEntity oEntity, boolean withLinks) { Object jpaEntity = newInstance(jpaEntityType.getJavaType()); if (jpaEntityType.getIdType().getPersistenceType() == PersistenceType.EMBEDDABLE) { EmbeddableType<?> et = (EmbeddableType<?>) jpaEntityType .getIdType(); JPAMember idMember = JPAMember.create( jpaEntityType.getId(et.getJavaType()), jpaEntity); Object idValue = newInstance(et.getJavaType()); idMember.set(idValue); } applyOProperties(em, jpaEntityType, oEntity.getProperties(), jpaEntity); if (withLinks) applyOLinks(em, jpaEntityType, oEntity.getLinks(), jpaEntity); return jpaEntity; }
} else { EntityType type = (EntityType) getFrom().getModel(); String parentIdAttribute = type.getId(type.getIdType().getJavaType()).getName(); if (!getFrom().get(parentIdAttribute).getJavaType().equals(joinRoot.get(property).getJavaType())) { throw new IllegalArgumentException("Type mismatch: cannot join " + type.getName() + "." + parentIdAttribute + " to " +
/** * if query orders are empty, then apply default ascending ordering * by root id attribute to prevent paging inconsistencies * * @param query * @param from * @param cb */ protected void mayBeAddDefaultOrderBy(CriteriaQuery<?> query, From<?,?> from, CriteriaBuilder cb) { if (query.getOrderList() == null || query.getOrderList().isEmpty()) { EntityType<?> fromEntityType = entityType; try { java.lang.reflect.Field sortField = getSortAnnotation(fromEntityType.getBindableJavaType()); if (sortField == null) query.orderBy(cb.asc(from.get(fromEntityType.getId(fromEntityType.getIdType().getJavaType()).getName()))); else { GraphQLDefaultOrderBy order = sortField.getAnnotation(GraphQLDefaultOrderBy.class); if (order.asc()) { query.orderBy(cb.asc(from.get(sortField.getName()))); } else { query.orderBy(cb.desc(from.get(sortField.getName()))); } } } catch (Exception ex) { //log.warn("In" + this.getClass().getName(), ex); } } }
public static EntityTypeDescriptor createSimpleEntityTypeDescriptor(EntityManagerFactory emf, Class<?> clazz) { EntityType<?> entityType = emf.getMetamodel().entity( clazz ); SingularAttribute<?, ?> idAttribute = entityType.getId( entityType.getIdType().getJavaType() ); return new EntityTypeDescriptor( clazz, new SingularIdOrder( idAttribute.getName() ) ); }