public void testMetamodelOnClauseWithLeftJoin() {
    EntityManager em = createEntityManager();
    Query query =
        em.createQuery(
            "Select e from Employee e left join e.address a on a.city = 'Ottawa' "
                + "where a.postalCode is not null");
    List baseResult = query.getResultList();

    Metamodel metamodel = em.getMetamodel();
    EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);
    EntityType<Address> entityAddr_ = metamodel.entity(Address.class);

    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
    Root<Employee> root = cq.from(entityEmp_);
    Join address = root.join(entityEmp_.getSingularAttribute("address"), JoinType.LEFT);
    address.on(qb.equal(address.get(entityAddr_.getSingularAttribute("city")), "Ottawa"));
    cq.where(qb.isNotNull(address.get(entityAddr_.getSingularAttribute("postalCode"))));
    List testResult = em.createQuery(cq).getResultList();

    clearCache();
    closeEntityManager(em);

    if (baseResult.size() != testResult.size()) {
      fail(
          "Criteria query using ON clause with a left join did not match JPQL results; "
              + baseResult.size()
              + " were expected, while criteria query returned "
              + testResult.size());
    }
  }
  public void testMetamodelOnClauseOverCollection() {
    EntityManager em = createEntityManager();
    Query query =
        em.createQuery("Select e from Employee e join e.phoneNumbers p on p.areaCode = '613'");
    List baseResult = query.getResultList();

    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
    Metamodel metamodel = em.getMetamodel();
    EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);
    EntityType<PhoneNumber> entityPhone_ = metamodel.entity(PhoneNumber.class);

    Root<Employee> root = cq.from(entityEmp_);
    Join phoneNumber = root.join(entityEmp_.getCollection("phoneNumbers"));
    phoneNumber.on(qb.equal(phoneNumber.get(entityPhone_.getSingularAttribute("areaCode")), "613"));
    List testResult = em.createQuery(cq).getResultList();

    clearCache();
    closeEntityManager(em);

    if (baseResult.size() != testResult.size()) {
      fail(
          "Criteria query using ON clause did not match JPQL results; "
              + baseResult.size()
              + " were expected, while criteria query returned "
              + testResult.size());
    }
  }
Ejemplo n.º 3
0
  @Bean
  public CacheManager cacheManager() {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager
        .getConfiguration()
        .setMaxBytesLocalHeap(
            env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

      String name = entity.getName();
      if (name == null || entity.getJavaType() != null) {
        name = entity.getJavaType().getName();
      }
      Assert.notNull(name, "entity cannot exist without a identifier");

      net.sf.ehcache.Cache cache = cacheManager.getCache(name);
      if (cache != null) {
        cache
            .getCacheConfiguration()
            .setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
        net.sf.ehcache.Ehcache decoratedCache =
            InstrumentedEhcache.instrument(metricRegistry, cache);
        cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
      }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
  }
  private void checkEntityId(Object entityId) {
    if (entityId == null) {
      throw new IllegalArgumentException("Invalid null entity id given");
    }

    EntityType<?> entityType =
        em.getMetamodel()
            .entity(
                joinManager
                    .getRootNodeOrFail(
                        "Paginated queries do not support multiple from clause elements!")
                    .getPropertyClass());
    Attribute<?, ?> idAttribute = JpaUtils.getIdAttribute(entityType);
    Class<?> idType = JpaUtils.resolveFieldClass(entityType.getJavaType(), idAttribute);

    if (!idType.isInstance(entityId)) {
      throw new IllegalArgumentException(
          "The type of the given entity id '"
              + entityId.getClass().getName()
              + "' is not an instance of the expected id type '"
              + idType.getName()
              + "' of the entity class '"
              + entityType.getJavaType().getName()
              + "'");
    }
  }
Ejemplo n.º 5
0
 @Test
 public void allClassMapping() throws Exception {
   Metamodel model = em.getEntityManagerFactory().getMetamodel();
   for (EntityType<?> entityType : model.getEntities()) {
     String entityName = entityType.getName();
     em.createQuery("select o from " + entityName + " o").getFirstResult();
     logger.info("ok: " + entityName);
   }
 }
Ejemplo n.º 6
0
 /**
  * Checks if entity is supclass of a @MappedSuperclass.
  *
  * @param subEntity Subentity
  * @param superEntity Possible super entity
  * @return true if super entity is subentity's superclass
  */
 private static boolean isSubClassOfMappedSuperClass(
     EntityType<?> subEntity, EntityType<?> superEntity) {
   boolean returnValue = false;
   if (subEntity.getSupertype().getSupertype() == null) {
     returnValue = false;
   } else if (subEntity.getSupertype().getSupertype().getJavaType() == superEntity.getJavaType()) {
     returnValue = true;
   }
   return returnValue;
 }
Ejemplo n.º 7
0
  @Before
  public void setUp() throws Exception {
    initMocks(this);
    final EntityType<Foo> foo = mock(EntityType.class);
    when(foo.getName()).thenReturn("foo");
    when(foo.getJavaType()).thenReturn(Foo.class);
    when(metamodel.entity(Foo.class)).thenReturn(foo);
    when(metamodel.getEntities()).thenReturn(new HashSet<EntityType<?>>(Arrays.asList(foo)));

    wrapper = new MetamodelWrapper(metamodel);
  }
Ejemplo n.º 8
0
 @Override
 public Map<String, Class<Entity>> getTableMap() {
   Map<String, Class<Entity>> map = new HashMap<String, Class<Entity>>();
   Metamodel metamodel = entityManager.getEntityManagerFactory().getMetamodel();
   Set<EntityType<?>> set = metamodel.getEntities();
   for (EntityType<?> entityType : set) {
     Class<Entity> clazz = (Class<Entity>) entityType.getJavaType();
     map.put(entityType.getName(), clazz);
   }
   return map;
 }
Ejemplo n.º 9
0
  @Test
  public void allClassMapping() throws Exception {
    Metamodel model = em.getEntityManagerFactory().getMetamodel();
    assertThat(model.getEntities()).as("No entity mapping found").isNotEmpty();

    for (EntityType entityType : model.getEntities()) {
      String entityName = entityType.getName();
      em.createQuery("select o from " + entityName + " o").getResultList();
      logger.info("ok: " + entityName);
    }
  }
 private synchronized void reloadCache(EntityManager em) {
   if (em == null || ref.get() != null) return;
   Metamodel metamodel = em.getMetamodel();
   Map<String, Class<?>> map = new HashMap<>(metamodel.getEntities().size() + 2);
   for (EntityType<?> entity : metamodel.getEntities()) {
     System.out.printf(
         "---  Carregando do Metamodel: %s [%s] \n", entity.getName(), entity.getJavaType());
     map.put(entity.getName(), entity.getJavaType());
   }
   ref = new SoftReference(map);
 }
Ejemplo n.º 11
0
  /**
   * Obtenir les association de premier niveau.
   *
   * @return la liste de toutes les associations.
   */
  protected List<Attribute<? super E, ?>> getAssociations() {
    initialiseMetaModel();

    List<Attribute<? super E, ?>> associations = new ArrayList<Attribute<? super E, ?>>();
    EntityType<E> typeEntite = metaModele.entity(classeEntite);
    for (Attribute<? super E, ?> attribut : typeEntite.getAttributes()) {
      if (isAssociation(attribut.getJavaType())) {
        associations.add(attribut);
      }
    }

    return associations;
  }
  public void testMetamodelCriteriaDelete() {
    if ((getPersistenceUnitServerSession()).getPlatform().isSymfoware()) {
      getPersistenceUnitServerSession()
          .logMessage(
              "Test simpleDelete skipped for this platform, "
                  + "Symfoware doesn't support UpdateAll/DeleteAll on multi-table objects (see rfe 298193).");
      return;
    }
    EntityManager em = createEntityManager();
    try {
      beginTransaction(em);
      int nrOfEmps =
          ((Number)
                  em.createQuery(
                          "SELECT COUNT(phone) FROM PhoneNumber phone where phone.owner.firstName is not null")
                      .getSingleResult())
              .intValue();

      Metamodel metamodel = em.getMetamodel();
      EntityType<PhoneNumber> entityPhone_ = metamodel.entity(PhoneNumber.class);
      EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);

      // test query "Delete Employee e where e.firstName is not null";
      CriteriaBuilder qb = em.getCriteriaBuilder();
      CriteriaDelete<PhoneNumber> cq = qb.createCriteriaDelete(PhoneNumber.class);
      Root<PhoneNumber> root = cq.from(entityPhone_);
      cq.where(
          qb.isNotNull(
              root.get(entityPhone_.getSingularAttribute("owner", Employee.class))
                  .get(entityEmp_.getSingularAttribute("firstName"))));
      Query testQuery = em.createQuery(cq);

      int updated = testQuery.executeUpdate();
      assertEquals(
          "testCriteriaDelete: wrong number of deleted instances" + updated, nrOfEmps, updated);

      // check database changes
      int nr =
          ((Number)
                  em.createQuery(
                          "SELECT COUNT(phone) FROM PhoneNumber phone where phone.owner.firstName is not null")
                      .getSingleResult())
              .intValue();
      assertEquals("testCriteriaDelete: found " + nr + " PhoneNumbers after delete all", 0, nr);
    } finally {
      if (isTransactionActive(em)) {
        rollbackTransaction(em);
      }
      closeEntityManager(em);
    }
  }
  public void testMetamodelCriteriaUpdate() {
    if ((getPersistenceUnitServerSession()).getPlatform().isSymfoware()) {
      getPersistenceUnitServerSession()
          .logMessage(
              "Test simpleUpdate skipped for this platform, "
                  + "Symfoware doesn't support UpdateAll/DeleteAll on multi-table objects (see rfe 298193).");
      return;
    }
    EntityManager em = createEntityManager();
    int nrOfEmps =
        ((Number)
                em.createQuery("SELECT COUNT(e) FROM Employee e where e.firstName is not null")
                    .getSingleResult())
            .intValue();

    Metamodel metamodel = em.getMetamodel();
    EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);

    // test query "UPDATE Employee e SET e.firstName = 'CHANGED' where e.firstName is not null";
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaUpdate<Employee> cq = qb.createCriteriaUpdate(Employee.class);
    Root<Employee> root = cq.from(entityEmp_);
    cq.set(root.get(entityEmp_.getSingularAttribute("firstName", String.class)), "CHANGED");
    cq.where(qb.isNotNull(root.get(entityEmp_.getSingularAttribute("firstName"))));

    beginTransaction(em);
    try {
      Query q = em.createQuery(cq);
      int updated = q.executeUpdate();
      assertEquals(
          "simpleCriteriaUpdateTest: wrong number of updated instances", nrOfEmps, updated);

      // check database changes
      int nr =
          ((Number)
                  em.createQuery("SELECT COUNT(e) FROM Employee e WHERE e.firstName = 'CHANGED'")
                      .getSingleResult())
              .intValue();
      assertEquals(
          "simpleCriteriaUpdateTest: unexpected number of changed values in the database",
          nrOfEmps,
          nr);
    } finally {
      if (isTransactionActive(em)) {
        rollbackTransaction(em);
      }
      closeEntityManager(em);
    }
  }
  // test ejbqlString = "Update Employee e set e.lastName = case when e.firstName = 'Bob' then
  // 'Jones' when e.firstName = 'Jill' then 'Jones' else '' end";
  public void testMetamodelComplexConditionCaseInCriteriaUpdate() {
    if ((getPersistenceUnitServerSession()).getPlatform().isSymfoware()) {
      getPersistenceUnitServerSession()
          .logMessage(
              "Test complexConditionCaseInUpdateTest skipped for this platform, "
                  + "Symfoware doesn't support UpdateAll/DeleteAll on multi-table objects (see rfe 298193).");
      return;
    }
    EntityManager em = createEntityManager();
    List<Employee> results = null;

    Metamodel metamodel = em.getMetamodel();
    EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);

    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaUpdate<Employee> cq = qb.createCriteriaUpdate(Employee.class);
    Root<Employee> root = cq.from(Employee.class);
    Case caseExp = qb.selectCase();
    caseExp.when(
        qb.equal(root.get(entityEmp_.getSingularAttribute("firstName", String.class)), "Bob"),
        "Jones");
    caseExp.when(
        qb.equal(root.get(entityEmp_.getSingularAttribute("firstName", String.class)), "Jill"),
        "Jones");
    caseExp.otherwise("");
    cq.set(root.get(entityEmp_.getSingularAttribute("lastName")), caseExp);

    beginTransaction(em);
    try {
      clearCache();

      em.createQuery(cq).executeUpdate();

      String verificationString = "select e from Employee e where e.lastName = 'Jones'";
      results = em.createQuery(verificationString).getResultList();
    } finally {
      if (isTransactionActive(em)) {
        rollbackTransaction(em);
      }
      closeEntityManager(em);
    }
    assertTrue("complexConditionCaseInUpdateTest - wrong number of results", results.size() == 2);
    for (Employee e : results) {
      assertTrue(
          "complexConditionCaseInUpdateTest wrong last name for - " + e.getFirstName(),
          e.getLastName().equals("Jones"));
    }
  }
Ejemplo n.º 15
0
  @SuppressWarnings("unchecked")
  private Class<E> getResultType(EntityManager em) {
    // We support this so users don't have to specify the query return type when using @Sync.
    if (resultTypeFqcn.equals("java.lang.Object")) {
      return (Class<E>) Object.class;
    }

    for (EntityType<?> et : em.getMetamodel().getEntities()) {
      if (et.getJavaType().getName().equals(resultTypeFqcn)) {
        return ((EntityType<E>) et).getJavaType();
      }
    }

    throw new IllegalStateException(
        "Result type " + resultTypeFqcn + " is not known to the EntityManager.");
  }
Ejemplo n.º 16
0
  @Override
  public List<Pessoa> listByEntity(Pessoa pessoa) {

    CriteriaBuilder cb = manager.getCriteriaBuilder();
    CriteriaQuery<Pessoa> query = cb.createQuery(Pessoa.class);
    Root<Pessoa> root = query.from(Pessoa.class);
    EntityType<Pessoa> typePessoa = manager.getMetamodel().entity(Pessoa.class);

    Predicate where1 = null, where2 = null, where3 = null, where4 = null;

    if (pessoa.getId() != null) {
      where1 = cb.equal(root.get("id"), pessoa.getId());
    }
    if (pessoa.getDtNascimento() != null) {
      where2 = cb.equal(root.get("dtNascimento"), pessoa.getDtNascimento());
    }
    if (pessoa.getTipoPessoa() != null) {
      where3 = cb.equal(root.get("tipoPessoa"), pessoa.getTipoPessoa());
    }
    if (pessoa.getNome() != null) {
      where4 =
          cb.equal(
              root.get(typePessoa.getDeclaredSingularAttribute("nome", String.class)),
              pessoa.getNome());
    }

    List<Predicate> predicados = new ArrayList<Predicate>();
    if (where1 != null) {
      predicados.add(where1);
    }
    if (where2 != null) {
      predicados.add(where2);
    }
    if (where3 != null) {
      predicados.add(where3);
    }
    if (where4 != null) {
      predicados.add(where4);
    }

    if (predicados.size() > 0) {
      query.where(cb.or(predicados.toArray(new Predicate[] {})));
    }
    return manager.createQuery(query).getResultList();
  }
Ejemplo n.º 17
0
 @Override
 public Map<String, Map<String, Class<?>>> getTableColumnMap() {
   Metamodel metamodel = entityManager.getEntityManagerFactory().getMetamodel();
   Set<EntityType<?>> entityTypes = metamodel.getEntities();
   Map<String, Map<String, Class<?>>> tableColumnMap =
       new HashMap<String, Map<String, Class<?>>>();
   for (EntityType<?> type : entityTypes) {
     EntityType<Entity> entityType = (EntityType<Entity>) type;
     Set<SingularAttribute<? super Entity, ?>> singularAttributes =
         entityType.getSingularAttributes();
     Map<String, Class<?>> columnMap = new HashMap<String, Class<?>>();
     for (SingularAttribute<? super Entity, ?> singularAttribute : singularAttributes) {
       columnMap.put(singularAttribute.getName(), singularAttribute.getJavaType());
     }
     tableColumnMap.put(entityType.getName(), columnMap);
   }
   return tableColumnMap;
 }
Ejemplo n.º 18
0
  public void run() {

    logger.debug("Starting protean server");

    if (entityManager != null) {
      for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) {
        if (entity.getJavaType().getAnnotation(Protean.class) == null) {
          continue;
        }

        getEntities().put(entity.getName(), entity);
      }
    }

    Thread thread = new Thread(server);
    thread.start();
    logger.info("Started protean server");
  }
Ejemplo n.º 19
0
  @SuppressWarnings("unchecked")
  private static String getEntityIdField(EntityManager em, Class entity) {

    String idProperty = "";

    Metamodel metamodel = em.getMetamodel();
    EntityType e = metamodel.entity(entity);
    Set<SingularAttribute> singularAttributes = e.getSingularAttributes();

    for (SingularAttribute singularAttribute : singularAttributes) {

      if (singularAttribute.isId()) {

        idProperty = singularAttribute.getName();
        break;
      }
    }

    return idProperty;
  }
  @SuppressWarnings("unchecked")
  private void applyNamedEntityGraphs(Collection<NamedEntityGraphDefinition> namedEntityGraphs) {
    for (NamedEntityGraphDefinition definition : namedEntityGraphs) {
      final EntityType entityType = metamodel.getEntityTypeByName(definition.getJpaEntityName());
      final EntityGraphImpl entityGraph =
          new EntityGraphImpl(definition.getRegisteredName(), entityType, this);

      final NamedEntityGraph namedEntityGraph = definition.getAnnotation();

      if (namedEntityGraph.includeAllAttributes()) {
        for (Object attributeObject : entityType.getAttributes()) {
          entityGraph.addAttributeNodes((Attribute) attributeObject);
        }
      }

      if (namedEntityGraph.attributeNodes() != null) {
        applyNamedAttributeNodes(namedEntityGraph.attributeNodes(), namedEntityGraph, entityGraph);
      }

      entityGraphs.put(definition.getRegisteredName(), entityGraph);
    }
  }
Ejemplo n.º 21
0
 @Bean
 public CacheManager cacheManager(JHipsterProperties jHipsterProperties) {
   log.debug("Starting Ehcache");
   cacheManager = net.sf.ehcache.CacheManager.create();
   cacheManager
       .getConfiguration()
       .setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap());
   log.debug("Registering Ehcache Metrics gauges");
   Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
   for (EntityType<?> entity : entities) {
     String name = entity.getName();
     if (name == null || entity.getJavaType() != null) {
       name = entity.getJavaType().getName();
     }
     Assert.notNull(name, "entity cannot exist without an identifier");
     reconfigureCache(name, jHipsterProperties);
     for (PluralAttribute pluralAttribute : entity.getPluralAttributes()) {
       reconfigureCache(name + "." + pluralAttribute.getName(), jHipsterProperties);
     }
   }
   EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
   ehCacheManager.setCacheManager(cacheManager);
   return ehCacheManager;
 }
  public void testMetamodelCriteriaUpdateEmbeddedField() {
    if ((getPersistenceUnitServerSession()).getPlatform().isSymfoware()) {
      getPersistenceUnitServerSession()
          .logMessage(
              "Test updateEmbeddedFieldTest skipped for this platform, "
                  + "Symfoware doesn't support UpdateAll/DeleteAll on multi-table objects (see rfe 298193).");
      return;
    }

    EntityManager em = createEntityManager();
    int nrOfEmps =
        ((Number)
                em.createQuery("SELECT COUNT(e) FROM Employee e where e.firstName is not null")
                    .getSingleResult())
            .intValue();

    Metamodel metamodel = em.getMetamodel();
    EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);
    javax.persistence.metamodel.EmbeddableType<EmploymentPeriod> embedEmpPeriod_ =
        metamodel.embeddable(EmploymentPeriod.class);

    Calendar startCalendar = Calendar.getInstance();
    startCalendar.set(1905, 11, 31, 0, 0, 0);
    java.sql.Date startDate = new java.sql.Date(startCalendar.getTime().getTime());

    // em.createQuery("UPDATE Employee e SET e.period.startDate=
    // :startDate").setParameter("startDate", startDate).executeUpdate();
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaUpdate<Employee> cq = qb.createCriteriaUpdate(Employee.class);
    Root<Employee> root = cq.from(entityEmp_);
    cq.set(
        root.get(entityEmp_.getSingularAttribute("period", EmploymentPeriod.class))
            .get(embedEmpPeriod_.getSingularAttribute("startDate", java.sql.Date.class)),
        startDate);

    beginTransaction(em);
    try {
      clearCache();

      int updated = em.createQuery(cq).executeUpdate();
      assertEquals(
          "testCriteriaUpdateEmbeddedField: wrong number of updated instances", nrOfEmps, updated);

      // check database changes
      int nr =
          ((Number)
                  em.createQuery(
                          "SELECT COUNT(e) FROM Employee e WHERE e.period.startDate = :startDate")
                      .setParameter("startDate", startDate)
                      .getSingleResult())
              .intValue();
      assertEquals(
          "testCriteriaUpdateEmbeddedField: unexpected number of changed values in the database",
          nrOfEmps,
          nr);
    } finally {
      if (isTransactionActive(em)) {
        rollbackTransaction(em);
      }
      closeEntityManager(em);
    }
  }
Ejemplo n.º 23
0
 @Override
 public void populateEntityDictionary(EntityDictionary dictionary) {
   for (EntityType entity : entityManagerFactory.getMetamodel().getEntities()) {
     dictionary.bindEntity(entity.getBindableJavaType());
   }
 }
Ejemplo n.º 24
0
 protected static String getEntityName(Class<?> clazz, EntityManager entityManager) {
   EntityType et = entityManager.getMetamodel().entity(clazz);
   return et.getName();
 }