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());
    }
  }
  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 <T> JpaEntityMetadata entityMetadataFor(Class<T> domainClass) {
   RepositoryCacheEntry entry = repositories.get(domainClass);
   if (null == entry.entityMetadata) {
     entry.entityMetadata = new JpaEntityMetadata(metamodel.entity(domainClass), this);
   }
   return entry.entityMetadata;
 }
Exemplo n.º 5
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);
  }
Exemplo n.º 6
0
 @Test
 public void testGetJoinColumnNamesFromElementCollectionFieldWithoutCollectionTable() {
   HashMap<String, String> joinColumnNames = new HashMap<String, String>();
   joinColumnNames.put("#", "employees_employee_id");
   PropertyDefinition emailAdresses = employeeDefinition.property("emailAddresses");
   SchemaMapper schemaMapper =
       JpaHibernateSchemaMapper.usingNamingStrategyOf(getEntityManagerFactory());
   assertEquals(
       joinColumnNames,
       JpaUtils.getJoinColumnNamesFromJpaAnnotatedField(
           schemaMapper, metamodel.entity(Employee.class), emailAdresses.getField()));
 }
Exemplo n.º 7
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 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"));
    }
  }
  ///// DELETE Criteria tests:
  public void simpleMetamodelCriteriaDeleteTest() {
    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();
    int nrOfEmps =
        ((Number) em.createQuery("SELECT COUNT(phone) FROM PhoneNumber phone").getSingleResult())
            .intValue();

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

    // test query "Delete PhoneNumber phone";
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaDelete<PhoneNumber> cq = qb.createCriteriaDelete(PhoneNumber.class);
    Root<PhoneNumber> root = cq.from(entityPhone_);

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

      // check database changes
      int nr =
          ((Number) em.createQuery("SELECT COUNT(phone) FROM PhoneNumber phone").getSingleResult())
              .intValue();
      assertEquals("simpleCriteriaDeleteTest: found " + nr + " employees after delete all", 0, nr);
    } finally {
      if (isTransactionActive(em)) {
        rollbackTransaction(em);
      }
      closeEntityManager(em);
    }
  }
Exemplo n.º 11
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;
  }
  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);
    }
  }
 public <T> EntityType<T> entityTypeFor(Class<T> domainClass) {
   return metamodel.entity(domainClass);
 }