List of usage examples for javax.persistence EntityManager getMetamodel
public Metamodel getMetamodel();
Metamodel
interface for access to the metamodel of the persistence unit. From source file:cz.datalite.dao.support.JpaEntityInformationSupport.java
/** * Creates a {@link JpaEntityInformation} for the given domain class and {@link javax.persistence.EntityManager}. * /*from ww w. j a va2s .c om*/ * @param domainClass must not be {@literal null}. * @param em must not be {@literal null}. * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> JpaEntityInformation<T, ?> getMetadata(Class<T> domainClass, EntityManager em) { assert (domainClass != null); assert (em != null); Metamodel metamodel = em.getMetamodel(); return new JpaMetamodelEntityInformation(domainClass, metamodel); }
From source file:org.jdal.dao.jpa.JpaUtils.java
/** * Initialize a entity. /*from www. jav a 2 s . co m*/ * @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); } } } } }
From source file:org.lightadmin.core.config.bootstrap.LightAdminBeanDefinitionRegistryPostProcessor.java
private Class createDynamicRepositoryClass(Class domainType, EntityManager entityManager) { EntityType entityType = entityManager.getMetamodel().entity(domainType); Class idType = entityType.getIdType().getJavaType(); return classFactory.createDynamicRepositoryClass(domainType, idType); }
From source file:org.lightadmin.core.config.bootstrap.LightAdminBeanDefinitionRegistryPostProcessor.java
private Iterable<Class<?>> managedEntities(EntityManager entityManager) { Set<Class<?>> managedEntities = newHashSet(); for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) { if (entity.getJavaType() != null) managedEntities.add(entity.getJavaType()); }//ww w.j a v a2s .co m return managedEntities; }
From source file:com.invariantproperties.sandbox.springentitylistener.listener.SpringEntityListenersConfigurer.java
@PostConstruct public void registerListeners() { // get registry so we can add listeners. HibernateEntityManagerFactory hemf = (HibernateEntityManagerFactory) entityManagerFactory; SessionFactory sf = hemf.getSessionFactory(); EventListenerRegistry registry = ((SessionFactoryImpl) sf).getServiceRegistry() .getService(EventListenerRegistry.class); final Set<Object> listeners = new HashSet<Object>(); EntityManager entityManager = null; try {//from www .ja v a 2s .c o m entityManager = hemf.createEntityManager(); // for every entity known to the system... for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) { // ... register event listeners for it. if (entity.getJavaType().isAnnotationPresent(SpringEntityListeners.class)) { SpringEntityListeners annotation = (SpringEntityListeners) entity.getJavaType() .getAnnotation(SpringEntityListeners.class); for (Class<?> beanClass : annotation.value()) { Map<String, ?> map = context.getBeansOfType(beanClass); listeners.addAll(map.values()); } } } } finally { if (entityManager != null) { entityManager.close(); } } // register adapter and listeners. HibernateEntityListenersAdapter adapter = new HibernateEntityListenersAdapter( new ArrayList<Object>(listeners), entityManagerFactory); registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(adapter); registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(adapter); registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(adapter); }
From source file:com.validation.manager.core.history.VersionableTest.java
@Test public void testVersioning() { try {//from w w w.j av a2 s. c o m DemoBuilder.buildDemoProject(); EntityManager em = DataBaseManager.getEntityManager(); //Populate with demo classes. for (EntityType<?> entity : em.getMetamodel().getEntities()) { if (Versionable.class.isAssignableFrom(entity.getJavaType())) { final String className = entity.getName(); System.out.println("Testing class: " + className); //Make sure they have at least one auditable field. List<Field> fields = FieldUtils.getFieldsListWithAnnotation(entity.getJavaType(), Auditable.class); assertEquals(false, fields.isEmpty()); //Get one from the demo data Versionable v = (Versionable) DataBaseManager .createdQuery("Select a from " + entity.getJavaType().getSimpleName() + " a").get(0); assertNotNull(v); v.updateHistory(); int count = v.getHistoryList().size(); for (Field f : fields) { //Now pick one of the Auditable fields assertEquals(count, v.getHistoryList().size()); History history = v.getHistoryList().get(v.getHistoryList().size() - 1); assertEquals(count == 1 ? "audit.general.creation" : "audit.general.modified", history.getReason()); assertEquals(0, history.getMajorVersion()); assertEquals(0, history.getMidVersion()); assertEquals(count++, history.getMinorVersion()); assertEquals(1, (int) history.getModifierId().getId()); assertNotNull(history.getModificationTime()); assertTrue(checkHistory(v)); assertFalse(Versionable.auditable(v)); System.out.println( "Changing field: " + f.getName() + " Type: " + f.getType().getSimpleName()); f.setAccessible(true); if (f.getType() == Integer.class) { Integer current = (Integer) f.get(v); Integer newValue = current + 1; showChange(current, newValue); f.set(v, newValue); } else if (f.getType() == String.class) { String current = (String) f.get(v); String newValue = current + 1; showChange(current, newValue); f.set(v, newValue); } else if (f.getType() == byte[].class) { byte[] current = (byte[]) f.get(v); byte[] append = "1".getBytes(); byte[] newValue = new byte[current.length + append.length]; showChange(current, newValue); f.set(v, newValue); } else if (f.getType() == Boolean.class) { Boolean current = (Boolean) f.get(v); Boolean newValue = !current; showChange(current, newValue); f.set(v, newValue); } else { fail("Unexpected field type: " + f.getType().getSimpleName()); } assertTrue(Versionable.auditable(v)); v.updateHistory(); assertEquals(count, v.getHistoryList().size()); history = v.getHistoryList().get(v.getHistoryList().size() - 1); assertEquals(0, history.getMajorVersion()); assertEquals(0, history.getMidVersion()); assertEquals(count, history.getMinorVersion()); assertEquals(1, (int) history.getModifierId().getId()); assertEquals("audit.general.modified", history.getReason()); assertNotNull(history.getModificationTime()); assertTrue(checkHistory(v)); assertFalse(Versionable.auditable(v)); int total = new HistoryJpaController(DataBaseManager.getEntityManagerFactory()) .getHistoryCount(); //Test for issue #25 https://github.com/javydreamercsw/validation-manager/issues/25 v = (Versionable) DataBaseManager.getEntityManager().find(entity.getJavaType(), DataBaseManager.getEntityManagerFactory().getPersistenceUnitUtil() .getIdentifier(v)); assertTrue(checkHistory(v)); assertEquals(total, new HistoryJpaController(DataBaseManager.getEntityManagerFactory()) .getHistoryCount()); assertEquals(count, v.getHistoryList().size()); } } } } catch (Exception ex) { Exceptions.printStackTrace(ex); fail(); } }
From source file:org.apache.openejb.util.proxy.QueryProxy.java
private <T> Query createFinderQuery(final EntityManager entityManager, final String methodName, final Class<T> entityType, final Object[] args) { final List<String> conditions = parseMethodName(methodName); final EntityType<T> et = entityManager.getMetamodel().entity(entityType); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Object> query = cb.createQuery(); final Root<T> from = query.from(entityType); query = query.select(from);/*from w w w . j a v a 2 s. co m*/ int i = 0; Predicate where = null; for (final String condition : conditions) { final SingularAttribute<? super T, ?> attribute = et.getSingularAttribute(condition); final Path<?> path = from.get(attribute); final Class<?> javaType = attribute.getType().getJavaType(); final Predicate currentClause; if (javaType.equals(String.class)) { currentClause = cb.like((Expression<String>) path, (String) args[i++]); } else if (Number.class.isAssignableFrom(javaType) || javaType.isPrimitive()) { currentClause = cb.equal(path, args[i++]); } else { LOGGER.warning("field " + condition + " not found, ignoring"); continue; } if (where == null) { where = currentClause; } else { where = cb.and(where, currentClause); } } if (where != null) { query = query.where(where); } // pagination final TypedQuery<?> emQuery = entityManager.createQuery(query); if (args != null && args.length == conditions.size() + 2 && isInt(args[args.length - 2].getClass()) && isInt(args[args.length - 1].getClass())) { final int first = (Integer) args[args.length - 2]; final int max = (Integer) args[args.length - 1]; emQuery.setFirstResult(first); emQuery.setMaxResults(max); } return emQuery; }
From source file:org.apache.ranger.service.XTrxLogService.java
private Predicate generatePredicate(SearchCriteria searchCriteria, EntityManager em, CriteriaBuilder criteriaBuilder, Root<VXXTrxLog> rootEntityType) { Predicate predicate = criteriaBuilder.conjunction(); Map<String, Object> paramList = searchCriteria.getParamList(); if (CollectionUtils.isEmpty(paramList)) { return predicate; }/*from www. j a v a 2s.c o m*/ Metamodel entityMetaModel = em.getMetamodel(); EntityType<VXXTrxLog> entityType = entityMetaModel.entity(VXXTrxLog.class); for (Map.Entry<String, Object> entry : paramList.entrySet()) { String key = entry.getKey(); for (SearchField searchField : searchFields) { if (!key.equalsIgnoreCase(searchField.getClientFieldName())) { continue; } String fieldName = searchField.getFieldName(); if (!StringUtils.isEmpty(fieldName)) { fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1) : fieldName; } Object paramValue = entry.getValue(); boolean isListValue = false; if (paramValue != null && paramValue instanceof Collection) { isListValue = true; } // build where clause depending upon given parameters if (SearchField.DATA_TYPE.STRING.equals(searchField.getDataType())) { // build where clause for String datatypes SingularAttribute attr = entityType.getSingularAttribute(fieldName); if (attr != null) { Predicate stringPredicate = null; if (SearchField.SEARCH_TYPE.PARTIAL.equals(searchField.getSearchType())) { String val = "%" + paramValue + "%"; stringPredicate = criteriaBuilder.like(rootEntityType.get(attr), val); } else { stringPredicate = criteriaBuilder.equal(rootEntityType.get(attr), paramValue); } predicate = criteriaBuilder.and(predicate, stringPredicate); } } else if (SearchField.DATA_TYPE.INT_LIST.equals(searchField.getDataType()) || isListValue && SearchField.DATA_TYPE.INTEGER.equals(searchField.getDataType())) { // build where clause for integer lists or integers datatypes Collection<Number> intValueList = null; if (paramValue != null && (paramValue instanceof Integer || paramValue instanceof Long)) { intValueList = new ArrayList<Number>(); intValueList.add((Number) paramValue); } else { intValueList = (Collection<Number>) paramValue; } for (Number value : intValueList) { SingularAttribute attr = entityType.getSingularAttribute(fieldName); if (attr != null) { Predicate intPredicate = criteriaBuilder.equal(rootEntityType.get(attr), value); predicate = criteriaBuilder.and(predicate, intPredicate); } } } else if (SearchField.DATA_TYPE.DATE.equals(searchField.getDataType())) { // build where clause for date datatypes Date fieldValue = (Date) paramList.get(searchField.getClientFieldName()); if (fieldValue != null && searchField.getCustomCondition() == null) { SingularAttribute attr = entityType.getSingularAttribute(fieldName); Predicate datePredicate = null; if (SearchField.SEARCH_TYPE.LESS_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.lessThan(rootEntityType.get(attr), fieldValue); } else if (SearchField.SEARCH_TYPE.LESS_EQUAL_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.lessThanOrEqualTo(rootEntityType.get(attr), fieldValue); } else if (SearchField.SEARCH_TYPE.GREATER_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.greaterThan(rootEntityType.get(attr), fieldValue); } else if (SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.greaterThanOrEqualTo(rootEntityType.get(attr), fieldValue); } else { datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue); } predicate = criteriaBuilder.and(predicate, datePredicate); } } } } return predicate; }
From source file:org.gvnix.web.datatables.util.DatatablesUtils.java
/** * Execute a select query on entityClass using <a * href="http://www.querydsl.com/">Querydsl</a> which enables the * construction of type-safe SQL-like queries. * //from ww w. j a v a 2 s. co m * @param entity builder for entity to use in search. Represents the entity * and gives access to its properties for query purposes * @param filterByAssociations (optional) for each related entity to join * contain as key the name of the association and as value the List * of related entity fields to filter by * @param orderByAssociations (optional) for each related entity to order * contain as key the name of the association and as value the List * of related entity fields to order by * @param entityManager {@code entityClass} {@link EntityManager} * @param datatablesCriterias datatables parameters for query * @param basePredicate (optional) base filter conditions * @param distinct use distinct query * @param conversionService required by filter-by-expression and rows-on-top * (otherwise optional) * @param messageSource required by filter-by-expression (otherwise * optional) * @param rowsOnTopIds (optional) array with id of rows to show on top of * result list * @return * @throws IllegalArgumentException */ public static <T, E extends Comparable<?>> SearchResults<T> findByCriteria(PathBuilder<T> entity, Map<String, List<String>> filterByAssociations, Map<String, List<String>> orderByAssociations, EntityManager entityManager, DatatablesCriterias datatablesCriterias, BooleanBuilder basePredicate, boolean distinct, ConversionService conversionService, MessageSource messageSource, Object[] rowsOnTopIds) throws IllegalArgumentException { // Check arguments aren't null Assert.notNull(entityManager); Assert.notNull(datatablesCriterias); // If null, create empty Map to avoid control code overload if (CollectionUtils.isEmpty(filterByAssociations)) { filterByAssociations = new HashMap<String, List<String>>(); } if (CollectionUtils.isEmpty(orderByAssociations)) { orderByAssociations = new HashMap<String, List<String>>(); } // true if data results must be paginated boolean isPaged = datatablesCriterias.getDisplaySize() != null && datatablesCriterias.getDisplaySize() > 0; // true if the search must take in account all columns boolean findInAllColumns = StringUtils.isNotEmpty(datatablesCriterias.getSearch()) && datatablesCriterias.hasOneFilterableColumn(); LOGGER.debug("findByCriteria for entity '{}' (paged={} findInAllColumns={})", entity.getType(), isPaged, findInAllColumns); // ----- Create queries ----- // query will take in account datatables search, order and paging // criterias JPAQuery query = new JPAQuery(entityManager); query = query.from(entity); // baseQuery will use base search values only in order to count // all for success paging JPAQuery baseQuery = new JPAQuery(entityManager); baseQuery = baseQuery.from(entity); // ----- Entity associations for Query JOINs, ORDER BY, ... ----- Map<String, PathBuilder<?>> associationMap = new HashMap<String, PathBuilder<?>>(); query = prepareQueryAssociationMap(entity, filterByAssociations, datatablesCriterias, findInAllColumns, query, associationMap); // ----- Query WHERE clauses ----- // Filters by column. Using BooleanBuilder, a cascading builder for // Predicate expressions BooleanBuilder filtersByColumnPredicate = new BooleanBuilder(); // Filters by table (for all columns) BooleanBuilder filtersByTablePredicate = new BooleanBuilder(); try { // Build the filters by column expression if (datatablesCriterias.hasOneFilteredColumn()) { filtersByColumnPredicate = prepareQueryFilterPart(entity, filterByAssociations, datatablesCriterias, associationMap, filtersByColumnPredicate, conversionService, messageSource); } // Build the query to search the given value in all columns filtersByTablePredicate = prepareQuerySearchPart(entity, filterByAssociations, datatablesCriterias, findInAllColumns, associationMap, filtersByTablePredicate, conversionService); } catch (Exception e) { LOGGER.error("Exception preparing filter for entity {}", entity.getType(), e); SearchResults<T> searchResults = new SearchResults<T>(new ArrayList<T>(0), 0, isPaged, new Long(org.apache.commons.lang3.ObjectUtils .defaultIfNull(datatablesCriterias.getDisplayStart(), 0)), new Long(org.apache.commons.lang3.ObjectUtils .defaultIfNull(datatablesCriterias.getDisplaySize(), 0)), 0); return searchResults; } // ----- Query ORDER BY ----- List<OrderSpecifier<?>> orderSpecifiersList = prepareQueryOrder(entity, orderByAssociations, datatablesCriterias, associationMap); // ----- Query results paging ----- Long offset = null; Long limit = null; if (isPaged) { limit = new Long(datatablesCriterias.getDisplaySize()); } if (datatablesCriterias.getDisplayStart() != null && datatablesCriterias.getDisplayStart() >= 0) { offset = new Long(datatablesCriterias.getDisplayStart()); } // ------- manage Rows-on-top ---- List<T> firstRows = null; // Decrease limits if firstRowsIds is used if (rowsOnTopIds != null) { LOGGER.trace("Prepare rows on top: {}", rowsOnTopIds); // Coherce row-on-top ids types Object[] cohercedRowsOnTopId = new Object[rowsOnTopIds.length]; EntityType<? extends T> entityMetamodel = entityManager.getMetamodel().entity(entity.getType()); // We always have just one id. This id can be an Embedded Id Class<?> idType = entityMetamodel.getIdType().getJavaType(); @SuppressWarnings("unchecked") SingularAttribute<? extends T, ?> idAttr = (SingularAttribute<? extends T, ?>) entityMetamodel .getId(idType); Object curId; for (int i = 0; i < rowsOnTopIds.length; i++) { curId = rowsOnTopIds[i]; if (curId.getClass() != idType) { cohercedRowsOnTopId[i] = conversionService.convert(curId, idType); } else { cohercedRowsOnTopId[i] = curId; } } // Create expression for rows-on-top BooleanExpression firstRowsInExpression = QuerydslUtils.createCollectionExpression(entity, idAttr.getName(), Arrays.asList(cohercedRowsOnTopId)); LOGGER.trace("Expression for rowsOnTop: {}", firstRowsInExpression); // Exclude firstRows from base query basePredicate = basePredicate.and(firstRowsInExpression.not()); LOGGER.trace("basePredicate to exclude rowsOnTop now is: {}", basePredicate); // Gets rows on top JPAQuery firstRowsQuery = new JPAQuery(entityManager); firstRowsQuery = firstRowsQuery.from(entity).where(firstRowsInExpression); LOGGER.trace("rowsOnTop query is: {}", firstRowsQuery); try { // TODO handle fieldSelector firstRows = firstRowsQuery.list(entity); } catch (PersistenceException exSql) { // Log query LOGGER.error("Error excecuting SQL for firstRow (sql = '{}' )", firstRowsQuery); throw exSql; } LOGGER.trace("Found {} rows for rowsOnTop", firstRows.size()); // Adjust limit with rows-on-top found if (limit != null) { LOGGER.trace("Update main query limit: {} --> {}", limit, limit - firstRows.size()); limit = limit - firstRows.size(); } } // ----- Execute the query ----- List<T> elements = null; // Compose the final query and update query var to be used to count // total amount of rows if needed if (distinct) { LOGGER.trace("Use distinct query!!!"); query = query.distinct(); } // Predicate for base query boolean hasBasePredicate = true; if (basePredicate == null) { basePredicate = new BooleanBuilder(); hasBasePredicate = false; } // query projection to count all entities without paging baseQuery.where(basePredicate); // query projection to be used to get the results and to count filtered // results query = query.where( basePredicate.and(filtersByColumnPredicate.getValue()).and(filtersByTablePredicate.getValue())); // Calculate the total amount of rows taking in account datatables // search and paging criterias. When results are paginated we // must execute a count query, otherwise the size of matched rows List // is the total amount of rows long totalResultCount = 0; if (isPaged) { try { totalResultCount = query.count(); } catch (PersistenceException exSql) { // Log query LOGGER.error("Error excecuting 'count' SQL: {}", query); throw exSql; } } if (offset == null) { offset = new Long(0); } else if (offset > totalResultCount) { // If offset value is bigger than total results, // offset needs start on 0 offset = new Long(0); } // QueryModifiers combines limit and offset QueryModifiers queryModifiers = new QueryModifiers(limit, offset); LOGGER.trace("Set limit={} offset={}", limit, offset); // List ordered and paginated results. An empty list is returned for no // results. query = query.orderBy(orderSpecifiersList.toArray(new OrderSpecifier[orderSpecifiersList.size()])); LOGGER.debug("Execute query: {}", query); try { elements = query.restrict(queryModifiers).list(entity); } catch (PersistenceException exSql) { // Log query LOGGER.error("Error excecuting SQL: {}", query); throw exSql; } if (!isPaged) { totalResultCount = elements.size(); } long totalBaseCount = totalResultCount; if (hasBasePredicate) { // Calculate the total amount of entities including base filters // only LOGGER.trace("Execute count query: {}", baseQuery); try { totalBaseCount = baseQuery.count(); } catch (PersistenceException exSql) { // Log query LOGGER.error("Error excecuting 'count' SQL: {}", baseQuery); throw exSql; } LOGGER.trace("Found : {}", totalBaseCount); } if (firstRows != null) { // Adjust result with rows-on-top totalResultCount = totalResultCount + firstRows.size(); totalBaseCount = totalBaseCount + firstRows.size(); elements.addAll(0, firstRows); } // Create a new SearchResults instance if (limit == null) { limit = totalBaseCount; } SearchResults<T> searchResults = new SearchResults<T>(elements, totalResultCount, isPaged, offset, limit, totalBaseCount); LOGGER.debug("findByCriteria: return {} rows from {} (offset={} limit={})", totalResultCount, totalBaseCount, offset, limit); return searchResults; }