@Override public void clear() { EntityManager em = emf.createEntityManager(); EntityTransaction txn = em.getTransaction(); try { // the clear operation often deadlocks - let's try several times for (int i = 0; ; ++i) { txn.begin(); try { log.trace("Clearing JPA Store"); String entityTable = em.getMetamodel().entity(configuration.entityClass()).getName(); @SuppressWarnings("unchecked") List<Object> items = em.createQuery("FROM " + entityTable).getResultList(); for (Object o : items) em.remove(o); if (configuration.storeMetadata()) { String metadataTable = em.getMetamodel().entity(MetadataEntity.class).getName(); Query clearMetadata = em.createQuery("DELETE FROM " + metadataTable); clearMetadata.executeUpdate(); } txn.commit(); em.clear(); break; } catch (Exception e) { log.trace("Failed to clear store", e); if (i >= 10) throw new JpaStoreException("Exception caught in clear()", e); } finally { if (txn != null && txn.isActive()) txn.rollback(); } } } finally { em.close(); } }
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()); } }
/** * Invoke byExample method for each not null x-to-one association when their pk is not set. This * allows you to search entities based on an associated entity's properties value. */ @SuppressWarnings("unchecked") public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne( ManagedType<T> mt, Root<T> mtPath, final T mtValue, SearchParameters sp, CriteriaBuilder builder) { List<Predicate> predicates = newArrayList(); for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) { if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { M2O m2oValue = (M2O) JpaUtil.getValue(mtValue, mt.getAttribute(attr.getName())); Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType(); Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr); ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType); if (m2oValue != null) { if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId())); } else { predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder)); } } } } return predicates; }
/** * Automatically retrieve ID from entity instance. * * @param obj The object from whom we need primary key * @return The corresponding primary key. */ @SuppressWarnings({"rawtypes", "unchecked"}) protected ID getIdFromEntity(T obj) { MetamodelUtils utils = new MetamodelUtils<T, ID>( (Class<T>) ClassUtils.getGenericTypeFromBean(this.service), em.getMetamodel()); return (ID) utils.getIdFromEntity(obj); }
@Override public Metamodel getMetamodel() { EntityManager em = getCurrent(); if (em != null) { return em.getMetamodel(); } em = createEntityManager(); try { return em.getMetamodel(); } finally { freeEntityManager(em); } }
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()); } }
@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 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); }
@Test @Sql( statements = { "INSERT INTO Person (id, firstName, lastName)" + " VALUES (42, 'John', 'Smith')" }) public void testGenerateSchema() throws Exception { entityManager.getMetamodel().entity(Person.class); // When the above call does not throw an exception, // the Person class is mapped as a persistent entity. Person p = entityManager.find(Person.class, 42L); assertEquals("John", p.getFirstName()); assertEquals("Smith", p.getLastName()); }
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")); } }
@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."); }
public <E> Predicate byExampleOnEmbeddable( Path<E> embeddablePath, final E embeddableValue, SearchParameters sp, CriteriaBuilder builder) { if (embeddableValue == null) { return null; } Class<E> type = embeddablePath.getModel().getBindableJavaType(); ManagedType<E> mt = em.getMetamodel().embeddable(type); // note: calling .managedType() does not work return JpaUtil.andPredicate( builder, byExample(mt, embeddablePath, embeddableValue, sp, builder)); }
public <T extends Identifiable<?>> Predicate byExampleOnEntity( Root<T> rootPath, final T entityValue, SearchParameters sp, CriteriaBuilder builder) { if (entityValue == null) { return null; } Class<T> type = rootPath.getModel().getBindableJavaType(); ManagedType<T> mt = em.getMetamodel().entity(type); List<Predicate> predicates = newArrayList(); predicates.addAll(byExample(mt, rootPath, entityValue, sp, builder)); predicates.addAll(byExampleOnCompositePk(rootPath, entityValue, sp, builder)); predicates.addAll( byExampleOnXToOne(mt, rootPath, entityValue, sp, builder)); // 1 level deep only predicates.addAll(byExampleOnManyToMany(mt, rootPath, entityValue, sp, builder)); return JpaUtil.andPredicate(builder, predicates); }
@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(); }
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"); }
///// 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); } }
@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; }
/* * (non-Javadoc) * * @see org.resthub.web.controller.GenericController#update(ID, T) */ @SuppressWarnings({"rawtypes", "unchecked"}) @Override @PUT @Path("/{id}") public T update(@PathParam("id") ID id, T entity) { Assert.notNull(id, "id cannot be null"); T retreivedEntity = this.service.findById(id); if (retreivedEntity == null) { throw new NotFoundException(); } MetamodelUtils utils = new MetamodelUtils<T, ID>( (Class<T>) ClassUtils.getGenericTypeFromBean(this.service), em.getMetamodel()); Serializable entityId = utils.getIdFromEntity(entity); if ((entityId != null) && !id.equals(this.getIdFromEntity(retreivedEntity))) { throw new WebApplicationException(Response.Status.CONFLICT); } if (null == entityId) { utils.setIdForEntity(entity, id); } return this.service.update(entity); }
@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; }
@PersistenceContext public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; this.metamodel = entityManager.getMetamodel(); }
public Metamodel getMetamodel() { return delegate.getMetamodel(); }
private void initialiseMetaModel() { if (metaModele == null) { metaModele = entityManager.getMetamodel(); } }
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); } }
@Override public Metamodel getMetamodel() { // TODO Auto-generated method stub return myEntityManager.getMetamodel(); }
protected static String getEntityName(Class<?> clazz, EntityManager entityManager) { EntityType et = entityManager.getMetamodel().entity(clazz); return et.getName(); }