Example usage for javax.persistence.metamodel EntityType getBindableJavaType

List of usage examples for javax.persistence.metamodel EntityType getBindableJavaType

Introduction

In this page you can find the example usage for javax.persistence.metamodel EntityType getBindableJavaType.

Prototype

Class<T> getBindableJavaType();

Source Link

Document

Return the Java type of the represented object.

Usage

From source file:com.clustercontrol.accesscontrol.util.ObjectPrivilegeUtil.java

/** ??? */
private static void createObjectPrivilegeMap() {
    if (m_objectPrivilegeMap == null || m_objectPrivilegeMap.size() == 0) {
        EntityManagerFactory emf = new JpaTransactionManager().getEntityManager().getEntityManagerFactory();
        Set<EntityType<?>> entityTypes = emf.getMetamodel().getEntities();
        String str = "";
        for (EntityType<?> entityType : entityTypes) {
            Class<?> clazz = entityType.getBindableJavaType();
            if (ObjectPrivilegeTargetInfo.class.isAssignableFrom(clazz)) {
                try {
                    HinemosObjectPrivilege hinemosObjectPrivilege = clazz
                            .getAnnotation(HinemosObjectPrivilege.class);
                    String objectType = hinemosObjectPrivilege.objectType();
                    if (hinemosObjectPrivilege.isModifyCheck()) {
                        str += "[" + objectType + "," + clazz + "] ";

                        if (m_objectPrivilegeMap.get(objectType) != null) {
                            m_log.warn("duplicate objectType=" + objectType);
                        }/*from   w  w w  .j  av  a2  s.c  o m*/
                        m_objectPrivilegeMap.put(objectType, clazz);
                    }
                } catch (Exception e) {
                    continue;
                }
            }
        }
        m_log.info("objectMap=" + str);
    }
}

From source file:com.sdl.odata.datasource.jpa.JPAEdmModelLoader.java

private List<Class<?>> discoverEntities() {
    Map<String, Class<?>> foundEntities = new HashMap<>();

    Metamodel metamodel = entityManagerFactory.getMetamodel();
    for (EntityType t : metamodel.getEntities()) {
        LOG.debug("We have a JPA Entity type: {}", t.getBindableJavaType().getCanonicalName());

        Class<?> entityType = t.getJavaType();

        foundEntities.put(entityType.getName(), entityType);
    }//from  w  w  w  . j  a v a 2 s  . c  o  m

    return new ArrayList<>(foundEntities.values());
}

From source file:ru.portal.gwt.gwtportal.server.GWTServiceImpl.java

@Override
public List<TableFieldsDto> getTableNameWithFields(TableDto tableDto) {
    List<TableFieldsDto> result = new ArrayList<>();
    Set<EntityType<?>> set = tableService.getEntityTypesByAnnotationClass(PortalTable.class);
    if (tableDto == null) {
        for (EntityType<?> entityType : set) {
            TableDto dto = new TableDto(entityType.getBindableJavaType().getName(),
                    entityType.getBindableJavaType().getAnnotation(PortalTable.class).title(),
                    entityType.getBindableJavaType().getName());
            result.add(dto);/*from ww  w.j  a  v a2s.  com*/

            //                List<User> users = new ArrayList<>();
            //                for (int i = 0; i < 150; i++) {
            //                    users.add(new User("admin" + i, "admin", true));
            //                }
            //                userService.save(users);
            //                
            //                
            //                List<Role> roles = new ArrayList<>();
            //                for (int i = 0; i < 200; i++) {
            //                    roles.add(new Role("admin" + i));
            //                }
            //                
            //                roleService.save(roles);

        }
    } else {
        for (EntityType<?> entityType : set) {
            if (entityType.getBindableJavaType().getName().equals(tableDto.getId())) {
                Field[] fields = entityType.getBindableJavaType().getDeclaredFields();
                for (Field field : fields) {
                    TableFieldsDto dto = new TableFieldsDto(
                            entityType.getBindableJavaType().getName() + field.getName(), field.getName(),
                            field.toString());
                    result.add(dto);
                }
            }
        }
    }
    return result;
}

From source file:ru.portal.services.TableServiceImpl.java

@Override
public Set<EntityType<?>> getEntityTypesByAnnotationClass(Class annotationClass) {
    Set<EntityType<?>> result = new HashSet<>();
    Set<EntityType<?>> set = em.getEntityManagerFactory().getMetamodel().getEntities();
    for (EntityType<?> entityType : set) {
        if (entityType.getBindableJavaType().getAnnotation(annotationClass) != null) {
            result.add(entityType);//from   ww  w  .ja  va  2 s .  c  o  m
        }
    }
    return result;

}

From source file:ru.portal.services.TableServiceImpl.java

@Override
public List<String> getTableOrViewMetaData(String tableOrViewName) {
    List<String> result = new ArrayList<>();
    Set<EntityType<?>> set = em.getEntityManagerFactory().getMetamodel().getEntities();
    for (EntityType<?> entityType : set) {
        if (entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(tableOrViewName)) {
                Field[] fields = entityType.getBindableJavaType().getDeclaredFields();
                for (Field field : fields) {
                    if (field.getAnnotation(Column.class) != null) {
                        result.add(field.getAnnotation(Column.class).name());
                    }/*from w  w  w.  j  a va2s . c  om*/
                    if (field.getAnnotation(Id.class) != null) {
                        result.add("id");
                    }
                }

            }
        }
    }
    return result;

}

From source file:ru.portal.controllers.RestController.java

private String generateTreeJson(Boolean isTable, String id) throws JSONException {
    JSONObject root = new JSONObject();
    JSONArray records = new JSONArray();

    root.put("records", records);

    Set<EntityType<?>> set = tableService.getEntityTypesByAnnotationClass(PortalTable.class);

    if (id == null) {
        for (EntityType<?> entityType : set) {
            JSONObject tableObject = new JSONObject();
            tableObject.put("table", true);
            tableObject.put("name", entityType.getBindableJavaType().getAnnotation(PortalTable.class).title());
            tableObject.put("id", entityType.getBindableJavaType().getName());
            records.put(tableObject);/*from   ww w.  ja  v  a2  s.  com*/
        }
    } else {
        for (EntityType<?> entityType : set) {
            if (entityType.getBindableJavaType().getName().equals(id)) {
                Field[] fields = entityType.getBindableJavaType().getDeclaredFields();
                for (Field field : fields) {
                    JSONObject tableObject = new JSONObject();
                    tableObject.put("table", false);
                    tableObject.put("name", field.getName());
                    tableObject.put("id", field);
                    records.put(tableObject);
                }
            }
        }
    }
    return root.toString();
}

From source file:ru.portal.services.TableServiceImpl.java

@Override
public Page<HashMap<String, String>> findAll(String tableOrViewName, Pageable pageable) {

    List<HashMap<String, String>> result = new ArrayList<>();

    EntityType<?> type = null;//w  w  w .jav a2 s.c om
    Set<EntityType<?>> set = em.getEntityManagerFactory().getMetamodel().getEntities();
    for (EntityType<?> entityType : set) {
        if (entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(tableOrViewName)) {
                type = entityType;
                break;
            }
        }
    }

    Long totalRows = 0L;

    if (type != null) {
        Class<?> bindableJavaType = type.getBindableJavaType();

        //count
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
        countQuery.select(criteriaBuilder.count(countQuery.from(bindableJavaType)));
        totalRows = em.createQuery(countQuery).getSingleResult();

        //select
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
        Root<?> root = cq.from(bindableJavaType);
        //          cq.select(root);
        if (pageable == null) {
            pageable = new PageRequest(0, 50);
        }

        TypedQuery<?> query = em.createQuery(cq);

        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<?> all = query.getResultList();

        List<String> columns = getTableOrViewMetaData(tableOrViewName);

        for (Object object : all) {

            HashMap<String, String> res = new HashMap<>(columns.size());
            Class<? extends Object> clazz = object.getClass();
            for (String fieldName : columns) {
                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object fieldValue = field.get(object);
                    res.put(fieldName, fieldValue.toString());
                    //TODO cast data integer long etc
                } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                        | IllegalAccessException ex) {
                    Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            result.add(res);
        }
    }

    PageImpl<HashMap<String, String>> list = new PageImpl<>(result, pageable, totalRows);
    return list;
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java

/**
 * Deletes ALL entities from the database
 *///from   ww  w  .  j a  v a 2s.  c o m
@After
public final void deleteAllEntities() {
    final EntityManager entityManager = getEntityManager();
    final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
    final Metamodel metamodel = entityManagerFactory.getMetamodel();
    Set<EntityType<?>> entityTypes = new LinkedHashSet<EntityType<?>>(metamodel.getEntities());

    do {
        final Set<EntityType<?>> failedEntitieTypes = new HashSet<EntityType<?>>();

        for (final EntityType<?> entityType : entityTypes) {
            final String entityClassName = entityType.getBindableJavaType().getName();

            try {
                this.executeInTransaction(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        logger.trace("Purging all: " + entityClassName);

                        final Query query = entityManager
                                .createQuery("SELECT e FROM " + entityClassName + " AS e");
                        final List<?> entities = query.getResultList();
                        logger.trace("Found " + entities.size() + " " + entityClassName + " to delete");
                        for (final Object entity : entities) {
                            entityManager.remove(entity);
                        }

                        return null;
                    }
                });
            } catch (DataIntegrityViolationException e) {
                logger.trace(
                        "Failed to delete " + entityClassName + ". Must be a dependency of another entity");
                failedEntitieTypes.add(entityType);
            }
        }

        entityTypes = failedEntitieTypes;
    } while (!entityTypes.isEmpty());

    //Reset all spring managed mocks after every test
    MockitoFactoryBean.resetAllMocks();
}

From source file:ru.portal.services.TableServiceImpl.java

/**
 * TODO    ManyToMany//ww  w . ja v a 2 s . co  m
 * @param entityClass
 * @param id
 * @return 
 */
@Override
public Map<EntityType<?>, Map<String, String>> findByEntityClassId(String entityClass, String id) {

    try {
        Class<?> cl = Class.forName(entityClass);
        EntityType<?> entityType = em.getEntityManagerFactory().getMetamodel().entity(cl);
        if (entityType != null && entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(entityClass)) {
                Class<?> bindableJavaType = entityType.getBindableJavaType();
                //select

                CriteriaBuilder cb = em.getCriteriaBuilder();
                CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
                Root<?> root = cq.from(User.class);

                cq.where(cb.equal(root.get("id"), Long.parseLong(id)));

                TypedQuery<?> query = em.createQuery(cq);
                ParameterExpression<Long> parameter = cb.parameter(Long.class, "id");
                //query.setParameter(parameter, Long.parseLong(id));
                //query.unwrap(org.hibernate.Query.class).getQueryString();

                Object result = query.getSingleResult();

                List<String> columns = getTableOrViewMetaData(entityClass);

                HashMap<String, String> res = new HashMap<>(columns.size());
                Class<? extends Object> clazz = result.getClass();
                for (String fieldName : columns) {
                    try {
                        Field field = clazz.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        Object fieldValue = field.get(result);
                        res.put(fieldName, fieldValue.toString());
                    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                            | IllegalAccessException ex) {
                        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                System.out.println(res);
                Map<EntityType<?>, Map<String, String>> hm = new HashMap<>();
                hm.put(entityType, res);
                return hm;

            }
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:ru.savvy.jpafilterbuilder.FilterCriteriaBuilder.java

/**
 * Resulting query with filters and orders, if orders are empty, than makes
 * default ascending ordering by root id to prevent paging confuses
 *
 * @return/*from   w  ww.ja v  a2s.c  o m*/
 */
public CriteriaQuery<T> getQuery() {
    CriteriaQuery<T> query = cb.createQuery(clazz);
    Root<T> root = query.from(clazz);
    applyFilters(root, query);
    applyOrders(root, query);

    // add default ordering
    if (query.getOrderList() == null || query.getOrderList().isEmpty()) {
        EntityType<T> entityType = root.getModel();
        try {
            Field sortField = getSortAnnotation(entityType.getBindableJavaType());
            if (sortField == null)
                query.orderBy(
                        cb.asc(root.get(entityType.getId(entityType.getIdType().getJavaType()).getName())));
            else {
                DefaultOrder order = sortField.getAnnotation(DefaultOrder.class);
                if (order.asc()) {
                    query.orderBy(cb.asc(root.get(sortField.getName())));
                } else {
                    query.orderBy(cb.desc(root.get(sortField.getName())));
                }

            }
        } catch (Exception ex) {
            logger.warn("In" + this.getClass().getName(), ex);
        }
    }
    return query;
}