项目:bootstrap
文件:CsvForJpa.java
/**
* Return JPA managed properties.
*
* @param <T>
* Bean type.
* @param beanType
* the bean type.
* @return the headers built from given type.
*/
public <T> String[] getJpaHeaders(final Class<T> beanType) {
// Build descriptor list respecting the declaration order
final OrderedFieldCallback fieldCallBack = new OrderedFieldCallback();
ReflectionUtils.doWithFields(beanType,fieldCallBack);
final List<String> orderedDescriptors = fieldCallBack.descriptorsOrdered;
// Now filter the properties
final List<String> descriptorsFiltered = new ArrayList<>();
final ManagedType<T> managedType = transactionManager.getEntityManagerFactory().getmetamodel().managedType(beanType);
for (final String propertyDescriptor : orderedDescriptors) {
for (final Attribute<?,?> attribute : managedType.getAttributes()) {
// Match only basic attributes
if (attribute instanceof Singularattribute<?,?> && propertyDescriptor.equals(attribute.getName())) {
descriptorsFiltered.add(attribute.getName());
break;
}
}
}
// Initialize the CSV reader
return descriptorsFiltered.toArray(new String[descriptorsFiltered.size()]);
}
项目:bootstrap
文件:CsvForJpa.java
/**
* Delete the managed entities. Self referencing rows are set to NULL before the deletion.
*
* @param beanTypes
* the ordered set to clean.
*/
public void cleanup(final Class<?>... beanTypes) {
// Clean the data
for (int i = beanTypes.length; i-- > 0;) {
final Class<?> entityClass = beanTypes[i];
final String update = em.getmetamodel().managedType(entityClass).getAttributes().stream().filter(a -> a.getJavaType().equals(entityClass))
.map(Attribute::getName).map(name -> name + "=NULL").collect(Collectors.joining(","));
if (update.length() > 0) {
// Clear the self referencing rows
em.createquery("UPDATE " + entityClass.getName() + " SET " + update).executeUpdate();
}
em.createquery("DELETE FROM " + entityClass.getName()).executeUpdate();
}
em.flush();
}
项目:rpb
文件:ByPatternUtil.java
/**
* Lookup entities having at least one String attribute matching the passed sp's pattern
*/
@SuppressWarnings("unused")
public <T> Predicate byPattern(Root<T> root,CriteriaQuery<?> query,CriteriaBuilder builder,final SearchParameters sp,final Class<T> type) {
if (!sp.hasSearchPattern()) {
return null;
}
List<Predicate> predicates = newArrayList();
EntityType<T> entity = em.getmetamodel().entity(type);
String pattern = sp.getSearchPattern();
for (Attribute<T,?> attr : entity.getDeclaredSingularattributes()) {
if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
continue;
}
if (attr.getJavaType() == String.class) {
predicates.add(JpaUtil.stringPredicate(root.get(attribute(entity,attr)),pattern,sp,builder));
}
}
return JpaUtil.orPredicate(builder,predicates);
}
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 visit(JpqlPath node,Set<TypeDeFinition> typeDeFinitions) {
Alias alias = new Alias(node.jjtGetChild(0).getValue());
Class<?> type = getType(alias,typeDeFinitions);
for (int i = 1; i < node.jjtGetNumChildren(); i++) {
ManagedType<?> managedType = forModel(metamodel).filter(type);
String attributeName = node.jjtGetChild(i).getValue();
Attribute<?,?> attribute = managedType.getAttribute(attributeName);
if (attribute instanceof Singularattribute
&& ((Singularattribute<?,?>)attribute).getType().getPersistenceType() == PersistenceType.BASIC
&& i < node.jjtGetNumChildren() - 1) {
String error = "Cannot navigate through simple property "
+ attributeName + " in class " + type.getName();
throw new PersistenceException(error);
}
type = attribute.getJavaType();
}
return false;
}
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;
}
项目:invesdwin-context-persistence
文件:Attributes.java
public static String extractNativesqlColumnName(final Attribute<?,?> attr) {
switch (attr.getPersistentAttributeType()) {
case BASIC:
case EMbedDED:
return attr.getName();
case ELEMENT_COLLECTION:
case ONE_TO_ONE:
case MANY_TO_ONE:
return attr.getName() + ID_SUFFIX;
case MANY_TO_MANY:
case ONE_TO_MANY:
throw new IllegalArgumentException(PersistentAttributeType.class.getSimpleName() + " ["
+ attr.getPersistentAttributeType() + "] is not supported!");
default:
throw UnkNownArgumentException.newInstance(PersistentAttributeType.class,attr.getPersistentAttributeType());
}
}
项目:invesdwin-context-persistence
文件:NativeJdbcIndexCreationHandler.java
@Transactional
private void dropIndexNewTx(final Class<?> entityClass,final Index index,final EntityManager em,final UniqueNameGenerator uniqueNameGenerator) {
Assertions.assertthat(index.columnNames().length).isGreaterThan(0);
final String comma = ",";
final String name;
if (Strings.isNotBlank(index.name())) {
name = index.name();
} else {
name = "idx" + entityClass.getSimpleName();
}
final StringBuilder cols = new StringBuilder();
final ManagedType<?> managedType = em.getmetamodel().managedType(entityClass);
for (final String columnName : index.columnNames()) {
if (cols.length() > 0) {
cols.append(comma);
}
final Attribute<?,?> column = Attributes.findAttribute(managedType,columnName);
cols.append(Attributes.extractNativesqlColumnName(column));
}
final String create = "DROP INDEX " + uniqueNameGenerator.get(name) + " ON " + entityClass.getSimpleName();
em.createNativeQuery(create).executeUpdate();
}
项目:OpenCyclos
文件:JpaQueryHandler.java
/**
* copies the persistent properties from the source to the destination entity
*/
public void copyProperties(final Entity source,final Entity dest) {
if (source == null || dest == null) {
return;
}
final ManagedType<?> MetaData = getClassmetamodel(source);
for (Attribute<?,?> attribute : MetaData.getAttributes()) {
// Skip the collections
if (attribute.isCollection()) {
PropertyHelper.set(dest,attribute.getName(),null);
} else {
PropertyHelper.set(dest,PropertyHelper.get(source,attribute.getName()));
}
}
}
项目:owsi-core-parent
文件:AbstractTestCase.java
/**
* Méthode permettant de s'assurer que les attributs des classes marquées @Entity ne seront pas sérialisés en
* "bytea" lors de leur écriture en base.
*
* @param classesAutorisees : concerne uniquement des classes matérialisées. Si une enum fait péter le test,c'est
* qu'il manque l'annotation @Enumerated ou que celle-ci prend EnumType.ORDINAL en paramètre
*/
protected void testmetamodel(List<Attribute<?,?>> ignoredAttributes,Class<?>... classesAutorisees) throws NoSuchFieldException,SecurityException {
List<Class<?>> listeAutorisee = Lists.newArrayList();
listeAutorisee.add(String.class);
listeAutorisee.add(Long.class);
listeAutorisee.add(Double.class);
listeAutorisee.add(Integer.class);
listeAutorisee.add(Float.class);
listeAutorisee.add(Date.class);
listeAutorisee.add(BigDecimal.class);
listeAutorisee.add(Boolean.class);
listeAutorisee.add(int.class);
listeAutorisee.add(long.class);
listeAutorisee.add(double.class);
listeAutorisee.add(boolean.class);
listeAutorisee.add(float.class);
for (Class<?> clazz : classesAutorisees) {
listeAutorisee.add(clazz);
}
for (EntityType<?> entityType : getEntityManager().getmetamodel().getEntities()) {
for (Attribute<?,?> attribute : entityType.getDeclaredAttributes()) {
testmetamodel(attribute,listeAutorisee,ignoredAttributes);
}
}
}
项目:random-jpa
文件:AttributeHelperTest.java
@Test
public void shouldReturnlistofFieldsForAtttributes() throws Exception {
EntityManagerProvider.init();
final List<Attribute<?,?>> attributes = new ArrayList<Attribute<?,?>>();
attributes.add(A_.id);
attributes.add(B_.id);
final List<Field> fields = AttributeHelper.getFields(attributes);
Assert.assertEquals(2,fields.size());
Assert.assertEquals("id",fields.get(0).getName());
Assert.assertEquals(A.class,fields.get(0).getDeclaringClass());
Assert.assertEquals("id",fields.get(1).getName());
Assert.assertEquals(B.class,fields.get(1).getDeclaringClass());
}
public void printPersistenceModel() {
metamodel metamodel = entityManager.getmetamodel();
Set<EntityType<? extends Object>> types = metamodel.getEntities();
for(EntityType<? extends Object> type : types) {
logger.log(Level.INFO,"--> Type: {0}",type);
Set attributes = type.getAttributes();
for(Object obj : attributes) {
logger.log(Level.INFO,"Name: {0}",((Attribute)obj).getName());
logger.log(Level.INFO,"isCollection: {0}",((Attribute)obj).isCollection());
logger.log(Level.INFO,((Attribute)obj).isAssociation());
logger.log(Level.INFO,((Attribute)obj).getPersistentAttributeType());
}
}
EntityType<Item> item = metamodel.entity(Item.class);
}
项目:jittrackGTS
文件:SpecificationHelper.java
private static boolean isPathJoin(Path<?> path) {
//todo how to avoid this?
/*
if (path instanceof PluralAttributePath) {
return true;
}
*/
if (Collection.class.isAssignableFrom(path.getJavaType()) || path.getJavaType().isArray()) {
return true;
}
Attribute.PersistentAttributeType persistentAttributeType = null;
if (path.getModel() instanceof Singularattribute) {
persistentAttributeType = ((Singularattribute) path.getModel()).getPersistentAttributeType();
}
if (persistentAttributeType == Attribute.PersistentAttributeType.MANY_TO_MANY ||
persistentAttributeType == Attribute.PersistentAttributeType.MANY_TO_ONE ||
persistentAttributeType == Attribute.PersistentAttributeType.ONE_TO_MANY ||
persistentAttributeType == Attribute.PersistentAttributeType.ONE_TO_ONE) {
return true;
}
return false;
}
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);
}
}
项目:javaee-lab
文件:JpaUtil.java
@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;
}
项目:javaee-lab
文件:JpaUtil.java
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();
}
}
项目:javaee-lab
文件:GenericRepository.java
@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);
}
}
}
}
}
项目:crnk-framework
文件:QueryUtil.java
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;
}
项目:crnk-framework
文件:QueryUtil.java
private static boolean containsMultiRelationJoin(Set<?> fetches) {
for (Object fetchObj : fetches) {
Fetch<?,?>) fetchObj;
Attribute<?,?> attr = fetch.getAttribute();
if (attr.isAssociation() && attr.isCollection())
return true;
if (containsMultiRelationFetch(fetch.getFetches()))
return true;
}
return false;
}
项目:bootstrap
文件:AbstractSpecification.java
/**
* Retrieve an existing join within the ones within the given root and that match to given attribute.
*
* @param from
* the from source element.
* @param attribute
* the attribute to join
* @return The join/fetch path if it exists.
* @param <U>
* The source type of the {@link Join}
*/
@SuppressWarnings("unchecked")
protected <U,T> PathImplementor<T> getJoinPath(final From<?,U> from,final Attribute<?,?> attribute) {
// Search within current joins
for (final Join<U,?> join : from.getJoins()) {
if (join.getAttribute().equals(attribute)) {
return fixAlias((Join<U,T>) join,aliasCounter);
}
}
return null;
}
项目:datatable-java
文件:DatatableHelper.java
/**
* Cree une expression Criteria API avec l'atribut de l'entité passé en parametre
*
* @param root
* entité JPA contenant le champ
* @param columnData
* nom du champ
* @param clazz
* class du champ
* @param <S>
* type du champ
* @return l'expression de l'atribut
*/
public static <S> Path<S> getExpression(final Root<?> root,final String columnData,final Class<S> clazz) {
if (!columnData.contains(DatatableSpecification.ATTRIBUTE_SEParaTOR)) {
// columnData is like "attribute" so nothing particular to do
return root.get(columnData);
}
// columnData is like "joinedEntity.attribute" so add a join clause
final String[] values = columnData.split(DatatableSpecification.ESCAPED_ATTRIBUTE_SEParaTOR);
final Attribute<?,?> attribute = root.getModel().getAttribute(values[0]);
if (attribute == null) {
throw new IllegalArgumentException(
"Colonne '" + values[0] + "' (" + columnData + ") introuvable depuis l'entité '" + root.getJavaType()
+ "'");
}
if (attribute.getPersistentAttributeType() == PersistentAttributeType.EMbedDED) {
// with @Embedded attribute
return root.get(values[0]).get(values[1]);
}
From<?,?> from = root;
for (int i = 0; i < values.length - 1; i++) {
Join<?,?> join = null;
for (final Join<?,?> joinCandidate : from.getJoins()) {
if (joinCandidate.getAttribute().getName().equals(values[i])) {
// LOGGER.debug("Trouve joint d'entite: '{}'",values[i]);
join = joinCandidate;
}
}
if (join == null) {
// LOGGER.debug("Joigant entite '{}'...",values[i]);
join = from.join(values[i],JoinType.INNER);
}
from = join;
}
return from.get(values[values.length - 1]);
}
项目:rpb
文件:ByExampleUtil.java
private <T> Object getValue(T example,Attribute<? super T,?> attr) {
try {
return ReflectionUtils.invokeMethod((Method) attr.getJavaMember(),example);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
项目:katharsis-framework
文件:QueryUtil.java
private static boolean containsMultiRelationFetch(Set<?> fetches) {
for (Object fetchObj : fetches) {
Fetch<?,?>) fetchObj;
Attribute<?,?> attr = fetch.getAttribute();
if (attr.isAssociation() && attr.isCollection())
return true;
if (containsMultiRelationFetch(fetch.getFetches()))
return true;
}
return false;
}
项目:katharsis-framework
文件:QueryUtil.java
private static boolean containsMultiRelationJoin(Set<?> fetches) {
for (Object fetchObj : fetches) {
Fetch<?,?>) fetchObj;
Attribute<?,?> attr = fetch.getAttribute();
if (attr.isAssociation() && attr.isCollection())
return true;
if (containsMultiRelationFetch(fetch.getFetches()))
return true;
}
return false;
}
private Path getSelectedEntityPath(Path selectedpath,Set<TypeDeFinition> typeDeFinitions) {
if (!selectedpath.hasParentPath()) {
return selectedpath;
}
Set<PersistentAttributeType> basicAttributeTypes = EnumSet.of(BASIC,EMbedDED,ELEMENT_COLLECTION);
Attribute<?,?> attribute
= Filter.attributeForPath(selectedpath).withmetamodel(metamodel).filter(typeDeFinitions);
while (selectedpath.hasParentPath() && basicAttributeTypes.contains(attribute.getPersistentAttributeType())) {
selectedpath = selectedpath.getParentPath();
attribute = Filter.attributeForPath(selectedpath).withmetamodel(metamodel).filter(typeDeFinitions);
}
return selectedpath;
}
@Override
protected ManagedType<?> transform(TypeDeFinition typeDeFinition) {
if (!path.hasSubpath()) {
return forModel(metamodel).filter(typeDeFinition.getType());
}
Attribute<?,?>)filter.transform(typeDeFinition);
if (attribute.isCollection()) {
return (ManagedType<?>)((PluralAttribute<?,?>)attribute).getElementType();
} else {
return (ManagedType<?>)((Singularattribute<?,?>)attribute).getType();
}
}
public <R> List<R> evaluateall(final Collection<?> root,String path) {
String[] pathelements = path.split("\\.");
List<Object> rootCollection = new ArrayList<Object>(root);
List<R> resultCollection = new ArrayList<R>();
for (String property: pathelements) {
resultCollection.clear();
for (Object rootObject: rootCollection) {
if (rootObject == null) {
continue;
}
ManagedType<?> managedType = forModel(metamodel).filter(rootObject.getClass());
if (containsAttribute(managedType,property)) {
Attribute<?,?> propertyMapping = managedType.getAttribute(property);
Object result = getValue(rootObject,propertyMapping);
if (result instanceof Collection) {
resultCollection.addAll((Collection<R>)result);
} else if (result != null) {
resultCollection.add((R)result);
}
} // else the property may be of a subclass and this path is ruled out by inner join on subclass table
}
rootCollection.clear();
for (Object resultObject: resultCollection) {
if (resultObject instanceof Collection) {
rootCollection.addAll((Collection<Object>)resultObject);
} else {
rootCollection.add(resultObject);
}
}
}
return resultCollection;
}
private boolean containsAttribute(ManagedType<?> managedType,String name) {
for (Attribute<?,?> attributes : managedType.getAttributes()) {
if (attributes.getName().equals(name)) {
return true;
}
}
return false;
}
private boolean visitJoin(Node node,Set<TypeDeFinition> typeDeFinitions,boolean innerJoin,boolean fetchJoin) {
Path fetchPath = new Path(node.jjtGetChild(0).toString());
Class<?> keyType = null;
Attribute<?,?> attribute = TypeDeFinition.Filter.attributeForPath(fetchPath)
.withmetamodel(metamodel)
.filter(typeDeFinitions);
Class<?> type;
if (attribute instanceof MapAttribute) {
MapAttribute<?,?> mapAttribute = (MapAttribute<?,?>)attribute;
keyType = mapAttribute.getKeyJavaType();
type = mapAttribute.getBindableJavaType();
} else {
type = TypeDeFinition.Filter.managedTypeForPath(fetchPath)
.withmetamodel(metamodel)
.filter(typeDeFinitions)
.getJavaType();
}
if (keyType != null) {
typeDeFinitions.add(new TypeDeFinition(keyType,fetchPath,innerJoin,fetchJoin));
}
if (node.jjtGetNumChildren() == 1) {
typeDeFinitions.add(new TypeDeFinition(type,fetchJoin));
} else {
Alias alias = getAlias(node);
typeDeFinitions.add(new TypeDeFinition(alias,type,fetchJoin));
}
return false;
}
private String getName(Bindable<?> bindable) {
if (bindable.getBindableType() == BindableType.ENTITY_TYPE) {
EntityType<?> entityType = (EntityType<?>)bindable;
return entityType.getName();
} else {
Attribute<?,?>)bindable;
return attribute.getName();
}
}
private MappedpathEvaluator createPathEvaluator() throws NoSuchFieldException {
metamodel metamodel = mock(metamodel.class);
SecurePersistenceUnitUtil persistenceUnitUtil = mock(SecurePersistenceUnitUtil.class);
EntityType userType = mock(EntityType.class);
EntityType groupType = mock(EntityType.class);
Attribute groupsAttribute = mock(Attribute.class);
Attribute fullHierarchyAttribute = mock(Attribute.class);
when(metamodel.managedType(User.class)).thenReturn(userType);
when(metamodel.managedType(Group.class)).thenReturn(groupType);
when(persistenceUnitUtil.isLoaded(any())).thenReturn(true);
when(persistenceUnitUtil.initialize(any())).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.getArgument(0);
}
});
when(userType.getAttributes()).thenReturn(Collections.singleton(groupsAttribute));
when(userType.getAttribute("groups")).thenReturn(groupsAttribute);
when(groupType.getAttributes()).thenReturn(Collections.singleton(fullHierarchyAttribute));
when(groupType.getAttribute("fullHierarchy")).thenReturn(fullHierarchyAttribute);
when(groupsAttribute.getName()).thenReturn("groups");
when(groupsAttribute.getJavaMember()).thenReturn(User.class.getDeclaredField("groups"));
when(fullHierarchyAttribute.getName()).thenReturn("fullHierarchy");
when(fullHierarchyAttribute.getJavaMember())
.thenReturn(Group.class.getDeclaredField("fullHierarchy"));
return new MappedpathEvaluator(metamodel,persistenceUnitUtil);
}
项目:invesdwin-context-persistence
文件:QueryByExampleHelper.java
/**
* When and=false,all criteria are combined with OR,else AND is used.
*
* @see <a href="http://stackoverflow.com/questions/2880209/jpa-findbyexample">Source</a>
*/
public TypedQuery<E> queryByExample(final String persistenceUnitName,final Class<E> genericType,final E example,final boolean and,final QueryConfig config) {
assertEntityExampleWithoutId(example);
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<E> cq = cb.createquery(genericType);
final Root<E> r = cq.from(genericType);
Predicate p = cb.conjunction();
final EntityType<E> et = em.getmetamodel().entity(genericType);
final Set<Attribute<? super E,?>> attrs = et.getAttributes();
boolean f@R_502_6447@tField = true;
for (final Attribute<? super E,?> attr : attrs) {
final String name = attr.getName();
final String javaName = attr.getJavaMember().getName();
final Field f = Reflections.findField(genericType,javaName);
Reflections.makeAccessible(f);
final Object value = Reflections.getField(f,example);
if (value != null) {
final Predicate pred = cb.equal(r.get(name),value);
if (and || f@R_502_6447@tField) {
p = cb.and(p,pred);
} else {
p = cb.or(p,pred);
}
f@R_502_6447@tField = false;
}
}
cq.select(r).where(p);
final TypedQuery<E> query = em.createquery(cq);
QueryConfig.configure(persistenceUnitName,query,config);
return query;
}
项目:invesdwin-context-persistence
文件:QueryByExampleHelper.java
private Query xByExample(final EntityManager em,final String queryStart,final boolean and) {
assertEntityExampleWithoutId(example);
final StringBuilder sb = new StringBuilder(queryStart);
sb.append(" FROM ");
sb.append(extractEntityName(genericType));
sb.append(" e WHERE 1 = 1");
final Map<String,Object> params = new HashMap<String,Object>();
final EntityType<E> et = em.getmetamodel().entity(genericType);
final Set<Attribute<? super E,example);
if (value != null) {
params.put(name,value);
if (and || f@R_502_6447@tField) {
sb.append(" AND ");
} else {
sb.append(" OR ");
}
sb.append("e.");
sb.append(name);
sb.append(" = :");
sb.append(name);
f@R_502_6447@tField = false;
}
}
final Query query = em.createquery(sb.toString());
for (final Entry<String,Object> param : params.entrySet()) {
query.setParameter(param.getKey(),param.getValue());
}
return query;
}
@SuppressWarnings("unchecked")
private List<String> determineJavaColumnNames(final PersistenceUnitContext puContext) {
final List<String> javaColumnNames = new ArrayList<String>();
final EntityManager em = puContext.getEntityManager();
final EntityType<E> et = (EntityType<E>) em.getmetamodel().entity(genericType);
final Set<Attribute<? super E,?>> attrs = et.getAttributes();
for (final Attribute<? super E,?> attr : attrs) {
final String javaName = attr.getJavaMember().getName();
javaColumnNames.add(javaName);
}
return javaColumnNames;
}
项目:invesdwin-context-persistence
文件:Attributes.java
public static Attribute<?,?> findAttribute(final ManagedType<?> managedType,final String columnName) {
try {
return managedType.getAttribute(Strings.removeEnd(columnName,Attributes.ID_SUFFIX));
} catch (final IllegalArgumentException e) {
return managedType.getAttribute(columnName);
}
}
项目:invesdwin-context-persistence
文件:NativeJdbcIndexCreationHandler.java
@Transactional
private void createIndexNewTx(final Class<?> entityClass,columnName);
cols.append(Attributes.extractNativesqlColumnName(column));
}
final String unique;
if (index.unique()) {
unique = " UNIQUE";
} else {
unique = "";
}
final String create = "CREATE" + unique + " INDEX " + uniqueNameGenerator.get(name) + " ON "
+ entityClass.getSimpleName() + " ( " + cols + " )";
em.createNativeQuery(create).executeUpdate();
}
项目:OpenCyclos
文件:JpaQueryHandler.java
项目:OpenCyclos
文件:JpaQueryHandler.java
public void resolveReference(final Object entity,String propertyName) {
final ManagedType<?> MetaData = getClassmetamodel(entity);
if (!MetaData.getAttributes().contains(propertyName)) {
throw new PropertyException(entity,propertyName);
}
Attribute<?,?> attribute = MetaData.getAttribute(propertyName);
resolveReference(entity,attribute);
}
项目:OpenCyclos
文件:JpaQueryHandler.java
private void resolveReference(final Object entity,Attribute<?,?> attribute) {
if (attribute.isCollection() && !Map.class.isAssignableFrom(attribute.getJavaType())) {
// Properties that are collections of other entities
final Collection<?> current = PropertyHelper.get(entity,attribute.getName());
if (current != null) {
boolean isEntityCollection = true;
final Collection<Entity> resolved = ClassHelper.instantiate(current.getClass());
for (final Object object : current) {
if (object != null && !(object instanceof Entity)) {
isEntityCollection = false;
break;
}
Entity e = (Entity) object;
if (object instanceof EntityReference) {
e = entityManager.find(EntityHelper.getRealClass(e),e.getId());
}
resolved.add(e);
}
if (isEntityCollection) {
PropertyHelper.set(entity,resolved);
}
}
} else if (attribute.isAssociation() && !Map.class.isAssignableFrom(attribute.getJavaType())) {
// Properties that are relationships to other entities
Entity rel = PropertyHelper.get(entity,attribute.getName());
if (rel instanceof EntityReference) {
rel = entityManager.find(EntityHelper.getRealClass(rel),rel.getId());
PropertyHelper.set(entity,rel);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。