下面列出了javax.persistence.JoinTable#javax.persistence.metamodel.Attribute 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String getColumnNameFromMetaModel(Attribute column) {
String columnName = null;
try {
if (isEclipseLinkOnClasspath()) {
columnName = ((AttributeImpl) column).getMapping().getField().getName();
} else if (isHibernateOnClasspath() && isEntityManagerActive()) {
AbstractEntityPersister entityMetadata = (AbstractEntityPersister) em().getEntityManagerFactory().unwrap(SessionFactory.class).getClassMetadata(column.getJavaMember().getDeclaringClass());
columnName = entityMetadata.getPropertyColumnNames(column.getName())[0];
}
} catch (Exception e) {
LOGGER.error("Could not extract database column name from column {} and type {}", column.getName(), column.getDeclaringType().getJavaType().getName(), e);
}
if (columnName == null) {
columnName = convertCase(column.getName(), config);
}
return columnName;
}
public static Optional<MetamodelAttribute> parse(
Elements elements, Types types, Element element) {
if (!(element instanceof VariableElement)) {
return Optional.empty();
}
VariableElement variableElement = (VariableElement) element;
if (variableElement.getKind() != FIELD) {
return Optional.empty();
}
TypeElement attributeTypeElement = elements.getTypeElement(Attribute.class.getCanonicalName());
if (!types.isSubtype(
types.erasure(variableElement.asType()), types.erasure(attributeTypeElement.asType()))) {
return Optional.empty();
}
return Optional.of(new MetamodelAttribute(variableElement));
}
public Predicate searchInAllAttributesPredicate(CriteriaBuilder builder, Root root, String text, List<String> includeOnlyFields) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
final String finalText = text;
Set<Attribute> attributes = root.getModel().getAttributes();
List<Predicate> orPredicates = new ArrayList<>();
for (Attribute a : attributes) {
boolean javaTypeIsString = a.getJavaType().getSimpleName().equalsIgnoreCase("string");
boolean shouldSearch = includeOnlyFields.isEmpty() || includeOnlyFields.contains(a.getName());
if (javaTypeIsString && shouldSearch) {
Predicate orPred = builder.like(root.get(a.getName()), finalText);
orPredicates.add(orPred);
}
}
return builder.or(orPredicates.toArray(new Predicate[orPredicates.size()]));
}
@Override
@SuppressWarnings({ "unchecked" })
public <Y> Path<Y> get(String attributeName) {
if ( ! canBeDereferenced() ) {
throw illegalDereference();
}
final Attribute attribute = locateAttribute( attributeName );
if ( attribute.isCollection() ) {
final PluralAttribute<X,Y,?> pluralAttribute = (PluralAttribute<X,Y,?>) attribute;
if ( PluralAttribute.CollectionType.MAP.equals( pluralAttribute.getCollectionType() ) ) {
return (PluralAttributePath<Y>) this.<Object,Object,Map<Object, Object>>get( (MapAttribute) pluralAttribute );
}
else {
return (PluralAttributePath<Y>) this.get( (PluralAttribute) pluralAttribute );
}
}
else {
return get( (SingularAttribute<X,Y>) attribute );
}
}
/**
* Verify via {@link EntityManager} if one of the attributes of the selected entity
* contains a embedded attribute.
* Return true if at least one embedded attribute is found or false if non embedded
* attribute is found.
*
* @param em according entity manager
* @param jpqlQuery query to verify
* @return true if at least one embedded attribute is found or false if non embedded
* attribute is found.
*/
private static boolean containsEmbeddedAttributes(EntityManager em, String jpqlQuery) {
Set<EntityType<?>> types = em.getMetamodel().getEntities();
int pos = jpqlQuery.indexOf("FROM ") + 5;
int lastpos = jpqlQuery.indexOf(" ", pos);
final String queriedEntity = jpqlQuery.substring(pos, lastpos);
for (EntityType<?> type : types) {
if(queriedEntity.equals(type.getName())) {
Set<Attribute<?, ?>> attributes = (Set<Attribute<?, ?>>) type.getAttributes();
for (Attribute<?, ?> attribute : attributes) {
if(jpqlQuery.contains(attribute.getName()) &&
attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
return true;
}
}
}
}
return false;
}
/**
* Count the number of E instances.
*
* @param entity a sample entity whose non-null properties may be used as search hint
* @param sp carries additional search information
* @param attributes the list of attributes to the property
* @return the number of entities matching the search.
*/
@Transactional
public int findPropertyCount(E entity, SearchParameters sp, List<Attribute<?, ?>> attributes) {
if (sp.hasNamedQuery()) {
return byNamedQueryUtil.numberByNamedQuery(sp).intValue();
}
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
Root<E> root = criteriaQuery.from(type);
Path<?> path = jpaUtil.getPath(root, attributes);
if (sp.getDistinct()) {
criteriaQuery = criteriaQuery.select(builder.countDistinct(path));
} else {
criteriaQuery = criteriaQuery.select(builder.count(path));
}
// predicate
Predicate predicate = getPredicate(criteriaQuery, root, builder, entity, sp);
if (predicate != null) {
criteriaQuery = criteriaQuery.where(predicate);
}
// construct order by to fetch or joins if needed
orderByUtil.buildJpaOrders(sp.getOrders(), root, builder, sp);
TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery);
applyCacheHints(typedQuery, sp);
return typedQuery.getSingleResult().intValue();
}
private void verifyPath(List<Attribute<?, ?>> attributes) {
Class<?> 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();
}
}
@Test
public void testBuildAssociationEndManyToOne() throws Exception {
InnerMock mockFirst = new InnerMock(Attribute.PersistentAttributeType.ONE_TO_MANY);
InnerMock mockSecond = new InnerMock(Attribute.PersistentAttributeType.MANY_TO_ONE);
JPAEdmAssociationEnd associationEnd = new JPAEdmAssociationEnd(mockFirst, mockSecond);
associationEnd.getBuilder().build();
assertEquals(EdmMultiplicity.MANY, associationEnd.getEdmAssociationEnd1().getMultiplicity());
assertEquals(EdmMultiplicity.ONE, associationEnd.getEdmAssociationEnd2().getMultiplicity());
assertEquals("SOID", associationEnd.getEdmAssociationEnd1().getType().getName());
assertEquals(new FullQualifiedName("salesorderprocessing", "SOID"), associationEnd.getEdmAssociationEnd1()
.getType());
assertTrue(associationEnd.isConsistent());
}
@SneakyThrows
protected Class getElementCollectionGenericType(Class type, Attribute attribute) {
Member member = attribute.getJavaMember();
if (member instanceof Field) {
Field field = (Field) member;
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
ParameterizedType rawType = (ParameterizedType) genericType;
Class elementCollectionClass = Class.forName(rawType.getActualTypeArguments()[0].getTypeName());
log.info("Map element collection generic type [{}] to [{}]", attribute.getName(), elementCollectionClass);
return elementCollectionClass;
}
}
return type;
}
@Override
@SuppressWarnings({ "unchecked" })
public Set<Attribute<? super X, ?>> getAttributes() {
HashSet attributes = new HashSet<Attribute<X, ?>>( declaredAttributes.values() );
if ( getSupertype() != null ) {
attributes.addAll( getSupertype().getAttributes() );
}
return attributes;
}
public Predicate handleCleanKeyCase(CriteriaBuilder builder, Root root, Join join, CriteriaQuery query, String key, Attribute a, Object val) {
boolean isValueCollection = val instanceof Collection;
boolean isValTextSearch = (val instanceof String) && ((String) val).contains("%");
if (isValueCollection) {
return handleCollection(builder, root, join, query, a, key, (Collection) val, false);
} else if (isValTextSearch) {
return createLikePredicate(builder, root, join, a, (String) val);
} else if(a.isCollection() && !a.isAssociation()) {
return createEqualityPredicate(builder, root, addJoinIfNotExists(root, a, false, isValueCollection), a, val);
} else {
return createEqualityPredicate(builder, root, join, a, val);
}
}
@Override
@SuppressWarnings({ "unchecked" })
public Attribute<? super X, ?> getAttribute(String name) {
Attribute<? super X, ?> attribute = declaredAttributes.get( name );
if ( attribute == null && getSupertype() != null ) {
attribute = getSupertype().getAttribute( name );
}
checkNotNull( "Attribute ", attribute, name );
return attribute;
}
/**
* Initialize a entity.
* @param em entity manager to use
* @param entity entity to initialize
* @param depth max depth on recursion
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void initialize(EntityManager em, Object entity, int depth) {
// return on nulls, depth = 0 or already initialized objects
if (entity == null || depth == 0) {
return;
}
PersistenceUnitUtil unitUtil = em.getEntityManagerFactory().getPersistenceUnitUtil();
EntityType entityType = em.getMetamodel().entity(entity.getClass());
Set<Attribute> attributes = entityType.getDeclaredAttributes();
Object id = unitUtil.getIdentifier(entity);
if (id != null) {
Object attached = em.find(entity.getClass(), unitUtil.getIdentifier(entity));
for (Attribute a : attributes) {
if (!unitUtil.isLoaded(entity, a.getName())) {
if (a.isCollection()) {
intializeCollection(em, entity, attached, a, depth);
}
else if(a.isAssociation()) {
intialize(em, entity, attached, a, depth);
}
}
}
}
}
@SuppressWarnings({"unchecked"})
protected BaseAttributeMetadata(
Property propertyMapping,
AbstractManagedType<X> ownerType,
Member member,
Attribute.PersistentAttributeType persistentAttributeType) {
this.propertyMapping = propertyMapping;
this.ownerType = ownerType;
this.member = member;
this.persistentAttributeType = persistentAttributeType;
final Class declaredType;
if ( member == null ) {
// assume we have a MAP entity-mode "class"
declaredType = propertyMapping.getType().getReturnedClass();
}
else if ( Field.class.isInstance( member ) ) {
declaredType = ( (Field) member ).getType();
}
else if ( Method.class.isInstance( member ) ) {
declaredType = ( (Method) member ).getReturnType();
}
else if ( MapMember.class.isInstance( member ) ) {
declaredType = ( (MapMember) member ).getType();
}
else {
throw new IllegalArgumentException( "Cannot determine java-type from given member [" + member + "]" );
}
this.javaType = accountForPrimitiveTypes( declaredType );
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setValuesToSet() {
if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.BASIC)) {
attributeSet.add((Attribute<? super String, String>) new JPAEdmAttribute(java.lang.String.class, "SOID"));
attributeSet.add((Attribute<? super String, String>) new JPAEdmAttribute(java.lang.String.class, "SONAME"));
} else if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.EMBEDDED)) {
attributeSet.add(new JPAEdmAttribute(JPAEdmEmbeddable.class, ComplexType.ComplexTypeA.clazz.getName()));
} else if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.MANY_TO_ONE)) {
attributeSet.add(new JPAEdmPluralAttribute());
}
}
@Override
public Attribute<?, ?> getJPAReferencedAttribute() {
JPAEdmAttribute<Object, String> refAttribute =
new JPAEdmAttribute<Object, String>(java.lang.String.class, "SOLITID");
return refAttribute;
}
private ManagedType<X> resolveManagedType(SingularAttribute<?, X> attribute) {
if ( Attribute.PersistentAttributeType.BASIC == attribute.getPersistentAttributeType() ) {
return null;
}
else if ( Attribute.PersistentAttributeType.EMBEDDED == attribute.getPersistentAttributeType() ) {
return (EmbeddableType<X>) attribute.getType();
}
else {
return (IdentifiableType<X>) attribute.getType();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setValuesToSet() {
attributeSet
.add((Attribute<? super String, String>) new JPAEdmAttribute(
java.lang.String.class, "SOID"));
attributeSet
.add((Attribute<? super String, String>) new JPAEdmAttribute(
java.lang.String.class, "SONAME"));
}
/**
* Convert the passed propertyPath into a JPA path.
* <p>
* Note: JPA will do joins if the property is in an associated entity.
*/
@SuppressWarnings("unchecked")
public static <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
Path<?> path = root;
for (Attribute<?, ?> attribute : attributes) {
boolean found = false;
// handle case when order on already fetched attribute
for (Fetch<E, ?> fetch : root.getFetches()) {
if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
path = (Join<E, ?>) fetch;
found = true;
break;
}
}
for (Join<E, ?> join : root.getJoins()) {
if (attribute.getName().equals(join.getAttribute().getName())) {
path = join;
found = true;
break;
}
}
if (!found) {
path = path.get(attribute.getName());
}
}
return (Path<F>) path;
}
@Test
public void testBuildAssociationEndOneToMany() throws Exception {
InnerMock mockFirst = new InnerMock(Attribute.PersistentAttributeType.MANY_TO_ONE);
InnerMock mockSecond = new InnerMock(Attribute.PersistentAttributeType.ONE_TO_MANY);
JPAEdmAssociationEnd associationEnd = new JPAEdmAssociationEnd(mockFirst, mockSecond);
associationEnd.getBuilder().build();
assertEquals(EdmMultiplicity.ONE, associationEnd.getEdmAssociationEnd1().getMultiplicity());
assertEquals(EdmMultiplicity.MANY, associationEnd.getEdmAssociationEnd2().getMultiplicity());
assertEquals("SOID", associationEnd.getEdmAssociationEnd1().getType().getName());
assertEquals(new FullQualifiedName("salesorderprocessing", "SOID"), associationEnd.getEdmAssociationEnd1()
.getType());
assertTrue(associationEnd.isConsistent());
}
public static void build(final JPAEdmAssociationEndView assocaitionEndView,
final JPAEdmEntityTypeView entityTypeView, final JPAEdmPropertyView propertyView) {
String namespace = buildNamespace(assocaitionEndView);
String name = entityTypeView.getEdmEntityType().getName();
FullQualifiedName fQName = new FullQualifiedName(namespace, name);
assocaitionEndView.getEdmAssociationEnd1().setType(fQName);
name = null;
String jpaEntityTypeName = null;
Attribute<?, ?> jpaAttribute = propertyView.getJPAAttribute();
if (jpaAttribute.isCollection()) {
jpaEntityTypeName = ((PluralAttribute<?, ?, ?>) jpaAttribute).getElementType().getJavaType()
.getSimpleName();
} else {
jpaEntityTypeName = propertyView.getJPAAttribute().getJavaType()
.getSimpleName();
}
JPAEdmMappingModelAccess mappingModelAccess = assocaitionEndView
.getJPAEdmMappingModelAccess();
if (mappingModelAccess != null
&& mappingModelAccess.isMappingModelExists()) {
name = mappingModelAccess.mapJPAEntityType(jpaEntityTypeName);
}
if (name == null) {
name = jpaEntityTypeName;
}
fQName = new FullQualifiedName(namespace, name);
assocaitionEndView.getEdmAssociationEnd2().setType(fQName);
}
private Predicate createLtePredicate(CriteriaBuilder builder, Root root, Attribute a, Object val) {
if (val instanceof String) {
return builder.lessThanOrEqualTo(builder.lower(root.get(a.getName())), ((String) val).toLowerCase());
} else if (val instanceof Integer) {
return builder.lessThanOrEqualTo(root.get(a.getName()), (Integer) val);
}
throw new IllegalArgumentException("val type not supported yet");
}
@Override
protected Attribute locateAttributeInternal(String attributeName) {
if ( ! canBeDereferenced() ) {
throw new IllegalArgumentException(
"Map key [" + getPathSource().getPathIdentifier() + "] cannot be dereferenced"
);
}
throw new UnsupportedOperationException( "Not yet supported!" );
}
private Predicate createGtPredicate(CriteriaBuilder builder, Root root, Attribute a, Object val) {
if (val instanceof String) {
return builder.greaterThan(builder.lower(root.get(a.getName())), ((String) val).toLowerCase());
} else if (val instanceof Integer) {
return builder.greaterThan(root.get(a.getName()), (Integer) val);
}
throw new IllegalArgumentException("val type not supported yet");
}
public PluralAttributeJoinSupport(
CriteriaBuilderImpl criteriaBuilder,
Class<E> javaType,
PathSource<O> pathSource,
Attribute<? super O,?> joinAttribute,
JoinType joinType) {
super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType );
}
@SuppressWarnings("WeakerAccess")
public <X> AttributeNodeImpl(
SessionFactoryImplementor sessionFactory,
ManagedType managedType,
Attribute<X, T> attribute) {
this.sessionFactory = sessionFactory;
this.managedType = managedType;
this.attribute = attribute;
}
private Predicate createLikePredicate(CriteriaBuilder builder, Root<T> root, Join join, Attribute a, String val) {
if (join == null) {
return builder.like(root.get(a.getName()), val);
}
else {
return builder.like(join.get(a.getName()), val);
}
}
private static boolean containsMultiRelationFetch(Set<?> fetches) {
for (Object fetchObj : fetches) {
Fetch<?, ?> fetch = (Fetch<?, ?>) fetchObj;
Attribute<?, ?> attr = fetch.getAttribute();
if (attr.isAssociation() && attr.isCollection())
return true;
if (containsMultiRelationFetch(fetch.getFetches()))
return true;
}
return false;
}
private boolean isPrimitive(Attribute attribute) {
String attributeJavaClass = attribute.getJavaType().getSimpleName().toLowerCase();
return attributeJavaClass.startsWith("int") ||
attributeJavaClass.startsWith("long") ||
attributeJavaClass.equals("boolean") ||
attributeJavaClass.equals("string") ||
attributeJavaClass.equals("float") ||
attributeJavaClass.equals("double");
}
private static boolean isBlob(final Attribute<?, ?> currentAttribute) {
if (currentAttribute != null) {
AnnotatedElement annotatedElement = (AnnotatedElement) currentAttribute.getJavaMember();
if (annotatedElement != null && annotatedElement.getAnnotation(Lob.class) != null) {
return true;
}
}
return false;
}