/** Test native query. */ public void testNativeQuery() { EntityManager em = createEntityManager(); MappedInteraction interaction = new MappedInteraction(); interaction.setProperty(OracleNoSQLPlatform.OPERATION, OracleNoSQLOperation.GET.name()); interaction.addArgumentValue("[Order-mapped," + existingOrder.id + "]", ""); Query query = em.unwrap(JpaEntityManager.class).createQuery(interaction); List result = query.getResultList(); if ((result.size() != 1) || (!(result.get(0) instanceof Record)) || !(((Record) result.get(0)).containsKey("[Order-mapped," + existingOrder.id + "]"))) { fail("Incorrect result: " + result); } interaction = new MappedInteraction(); interaction.setProperty(OracleNoSQLPlatform.OPERATION, OracleNoSQLOperation.GET.name()); interaction.setProperty(OracleNoSQLPlatform.TIMEOUT, "1000"); interaction.setProperty(OracleNoSQLPlatform.CONSISTENCY, "ABSOLUTE"); interaction.addArgumentValue("ID", existingOrder.id); query = em.unwrap(JpaEntityManager.class).createQuery(interaction, Order.class); result = query.getResultList(); if ((result.size() != 1) || (!(result.get(0) instanceof Order))) { fail("Incorrect result: " + result); } }
/** Check if eviction of entity cache is working */ public String evict2LCCheck(String CACHE_REGION_NAME) { EntityManager em = emf.createEntityManager(); Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics(); stats.clear(); SecondLevelCacheStatistics emp2LCStats = stats.getSecondLevelCacheStatistics(CACHE_REGION_NAME + "Employee"); try { createEmployee(em, "Jan", "Ostrava", 20); createEmployee(em, "Martin", "Brno", 30); assertEquals( "There are 2 puts in the 2LC" + generateEntityCacheStats(emp2LCStats), 2, emp2LCStats.getPutCount()); assertTrue( "Expected entities stored in the cache" + generateEntityCacheStats(emp2LCStats), emp2LCStats.getElementCountInMemory() > 0); // evict cache and check if is empty emf.getCache().evictAll(); assertEquals( "Expected no entities stored in the cache" + generateEntityCacheStats(emp2LCStats), 0, emp2LCStats.getElementCountInMemory()); } catch (AssertionError e) { return e.getMessage(); } finally { em.close(); } return "OK"; }
public JasperPrint RelatorioDataProduto( java.sql.Timestamp data1, java.sql.Timestamp data2, int idProduto) throws SQLException { String path = JPAUtil.getConfRelatorio(); EntityManager em = new JPAUtil().getEntityManager(); em.getTransaction().begin(); Session hibernateSession = em.unwrap(Session.class); hibernateSession.doWork( new org.hibernate.jdbc.Work() { @Override public void execute(Connection con) throws SQLException { try { HashMap map = new HashMap(); map.put("DataInicio", data1); map.put("DataFinal", data2); map.put("Produto", idProduto); rel = JasperFillManager.fillReport(path + "GeralDatasProduto.jasper", map, con); JasperViewer jrviewer = new JasperViewer(rel, false); jrviewer.show(); } catch (JRException ex) { Logger.getLogger(RelatorioController.class.getName()).log(Level.SEVERE, null, ex); } } }); return rel; }
@Override public void conversationPausing(Conversation conversation) { EntityManager em = conversation.getEntityManager(); if (em != null) { boolean needToReleaseConnection = false; if (unbindEntityManager(conversation.getEntityManager())) { needToReleaseConnection = true; } if (!conversation.isEntityManagerStillNeeded()) { em.close(); conversation.setEntityManager(null); if (log.isDebugEnabled()) { log.debug( "conv. " + conversation.getId() + " pausing: conversation's entityManager closed: " + em.hashCode()); } } else if (needToReleaseConnection) { // _HACK_ as we depend on Hibernate // Note: normally we should not have to do this as we have configured hibernate // with hibernate.connection.release_mode=after_transaction // But we load some lazy data non transactionnally from the view... Session session = em.unwrap(Session.class); session.disconnect(); // will be reconnected automatically as needed. } } }
@Path("deleteprop/{typename}/{propname}") @GET public XMLEntityMappings deleteProp( @PathParam("typename") String typeName, @PathParam("propname") String propName) throws Exception { ClassAccessor entity = JpaMapHelper.findClassAccessor(DynamicMetaSource.getEntityMaps(), typeName); Attribute<?, ?> attr = JpaMetamodelHelper.getAttribute(typeName, propName); if (JpaMapHelper.findPropertyBbyMappedBy( JpaMetamodelHelper.getAttributeType(attr).getSimpleName(), propName) != null) { throw new CodedExceptionImpl( PROP_REFERED, "Deletion can not be performed. Target Property is referred by other types"); } EntityManager eManager = App.getEM(); eManager.getTransaction().begin(); Connection connection = eManager.unwrap(Connection.class); for (String sql : JpaHelper.deletePropDBStructure(eManager, typeName, propName)) { LOGGER.info(sql); connection.createStatement().execute(sql); } eManager.getTransaction().commit(); JpaMapHelper.deleteProp(entity, propName); App.getPersistenceUnit().refresh(false); mapPersister.save(DynamicMetaSource.getEntityMaps()); return DynamicMetaSource.getEntityMaps(); }
@Test public void testWrappedFromEntityManagerAPI() throws Exception { buildArchive(); final EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpajtastandalone"); assertThat(HibernateEntityManagerFactory.class.isAssignableFrom(emf.getClass())).isTrue(); SessionFactory factory = ((HibernateEntityManagerFactory) emf).getSessionFactory(); assertThat(factory.getClass()).isEqualTo(OgmSessionFactory.class); Session s = factory.openSession(); assertThat(s.getClass()).isEqualTo(OgmSession.class); assertThat(s.getSessionFactory().getClass()).isEqualTo(OgmSessionFactory.class); Cavalier cavalier = new Cavalier(); cavalier.setName("Caroline"); EntityManager em = emf.createEntityManager(); assertThat(em.unwrap(Session.class).getClass()).isEqualTo(OgmSession.class); assertThat(em.getDelegate().getClass()).isEqualTo(OgmSession.class); s.save(cavalier); Cavalier c = (Cavalier) s.get(Cavalier.class, cavalier.getId()); assertTrue(c.getId().equals(cavalier.getId())); assertTrue(c.getName().equals(cavalier.getName())); em.close(); emf.close(); }
/** Check if disabling 2LC works as expected */ public String disabled2LCCheck() { EntityManager em = emfNo2LC.createEntityManager(); Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics(); stats.clear(); try { // check if entities are NOT cached in 2LC String names[] = stats.getSecondLevelCacheRegionNames(); assertEquals("There aren't any 2LC regions.", 0, names.length); createEmployee(em, "Martin", "Prague 132", 1); assertEquals("There aren't any puts in the 2LC.", 0, stats.getSecondLevelCachePutCount()); // check if queries are NOT cached in 2LC Employee emp = getEmployeeQuery(em, 1); assertNotNull("Employee returned", emp); assertEquals("There aren't any query puts in the 2LC.", 0, stats.getQueryCachePutCount()); // cleanup em.remove(emp); } catch (AssertionError e) { return e.getMessage(); } finally { em.close(); } return "OK"; }
@Override public <T> T unwrap(Class<T> cls) { EntityManager em = getCurrent(); if (em != null) { return em.unwrap(cls); } em = createEntityManager(); try { return em.unwrap(cls); } finally { freeEntityManager(em); } }
public Connection getJDBCConnection() { if (connection == null) { em.getTransaction().begin(); connection = em.unwrap(java.sql.Connection.class); } return connection; }
/** * Busca parâmetro do sistema pelo id * * @throws DatabaseException */ public ParametrosSistema buscarPorChave(Integer idParametro) throws Exception { final Session session = em.unwrap(Session.class); final Criteria crit = CriaCriteria.createCriteria(ParametrosSistema.class, session); crit.add(Restrictions.eq("idParametroSistema", idParametro)); return (ParametrosSistema) crit.uniqueResult(); }
public static void jdbc(EntityManager em) { Session session = em.unwrap(Session.class); session.doWork( new Work() { @Override public void execute(Connection connection) throws SQLException { System.out.println("jdbc connection을 얻다"); } }); }
@SuppressWarnings("unchecked") public List<Usuario> filtrado(UsuarioFilter filtro) { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(Usuario.class); if (StringUtils.isNotBlank(filtro.getNome())) { criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE)); } return criteria.addOrder(Order.asc("nome")).list(); }
@Transactional public void removerPorUsuario(Integer idUsuario) { try { Session session = manager.unwrap(Session.class); String hql = "delete from TbFuncionalidadeUsuario where tbUsuario.id = :idUsuario"; Query qrDelete = session.createQuery(hql).setInteger("idUsuario", idUsuario); qrDelete.executeUpdate(); } catch (PersistenceException e) { throw new NegocioException(Msgs.MSG_08); } }
@Override // TODO: Replace UserServiceException by new UserDAOExceptions or something public Integer addUser(User user) throws UserServiceException { final TypedQuery<User> q = em.createNamedQuery("User.findByUsername", User.class); q.setParameter("username", user.getUsername()); if (!q.getResultList().isEmpty()) { throw new UserServiceException("User " + user.getUsername() + " already exists"); } final Session session = em.unwrap(Session.class); session.saveOrUpdate(user); return user.getId(); }
/** * Utility for creating queries based on naturalId. The caller MUST be annotated with {@link * OpenEntityManager} or {@link Transactional} so that the Hibernate specific extensions are * available. */ protected final <T> NaturalIdQuery<T> createNaturalIdQuery(Class<T> entityType) { final EntityManager entityManager = this.getEntityManager(); final Session session; try { session = entityManager.unwrap(Session.class); } catch (IllegalStateException e) { throw new IllegalStateException( "The DAO Method that calls createNaturalIdQuery must be annotated with @OpenEntityManager or @Transactional", e); } final NaturalIdLoadAccess naturalIdLoadAccess = session.byNaturalId(entityType); return new NaturalIdQuery<T>(entityType, naturalIdLoadAccess); }
/** Evicts all query cache regions */ public void evictQueryCache() { EntityManager em = emf.createEntityManager(); try { // this should evict query cache em.unwrap(Session.class).getSessionFactory().getCache().evictQueryRegions(); } catch (Exception e) { e.printStackTrace(); } finally { em.close(); } }
@SuppressWarnings("unchecked") public List<Pais> filtrados(PaisFilter filtro) { Session session = manager.unwrap(Session.class); Criteria criteria = session.createCriteria(Pais.class); if (StringUtils.isNotBlank(filtro.getDescricao())) { criteria.add(Restrictions.ilike("descricao", filtro.getDescricao(), MatchMode.ANYWHERE)); } if (filtro.getCodigo() != null) { criteria.add(Restrictions.eq("codigo", filtro.getCodigo())); } return criteria.addOrder(Order.asc("descricao")).list(); }
private void withScroll() { withBatch(); // tag::batch-session-scroll-example[] EntityManager entityManager = null; EntityTransaction txn = null; ScrollableResults scrollableResults = null; try { entityManager = entityManagerFactory().createEntityManager(); txn = entityManager.getTransaction(); txn.begin(); int batchSize = 25; Session session = entityManager.unwrap(Session.class); scrollableResults = session .createQuery("select p from Person p") .setCacheMode(CacheMode.IGNORE) .scroll(ScrollMode.FORWARD_ONLY); int count = 0; while (scrollableResults.next()) { Person Person = (Person) scrollableResults.get(0); processPerson(Person); if (++count % batchSize == 0) { // flush a batch of updates and release memory: entityManager.flush(); entityManager.clear(); } } txn.commit(); } catch (RuntimeException e) { if (txn != null && txn.isActive()) txn.rollback(); throw e; } finally { if (scrollableResults != null) { scrollableResults.close(); } if (entityManager != null) { entityManager.close(); } } // end::batch-session-scroll-example[] }
@SuppressWarnings("unchecked") public List<Usuario> filtrados(UsuarioFilter filtro) { Session session = manager.unwrap(Session.class); Criteria criteria = session.createCriteria(Usuario.class).createAlias("profissional", "p"); if (StringUtils.isNotBlank(filtro.getNomeProfissional())) { criteria.add(Restrictions.ilike("p.nome", filtro.getNomeProfissional(), MatchMode.ANYWHERE)); } if (StringUtils.isNotBlank(filtro.getLogin())) { criteria.add(Restrictions.ilike("login", filtro.getLogin(), MatchMode.ANYWHERE)); } return criteria.addOrder(Order.asc("login")).list(); }
@Before public void init() throws SQLException { emf = Persistence.createEntityManagerFactory("unit3"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Connection con = em.unwrap(java.sql.Connection.class); Statement s = con.createStatement(); s.execute("drop table entity if exists"); s.execute( "create table entity (ID INT primary key, NAME VARCHAR(50), type VARCHAR(50), relatedentity_id INT) "); s.execute("drop table related if exists"); s.execute("create table related (ID INT primary key, NAME VARCHAR(50), type VARCHAR(50)) "); em.getTransaction().commit(); em.close(); }
/** * Performs 2 query calls, first call put query in the cache and second should hit the cache * * @param id Employee's id in the query */ public String queryCacheCheck(String id) { EntityManager em = emf.createEntityManager(); Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics(); stats.clear(); try { // the nextTimestamp from infinispan is "return System.currentTimeMillis() / 100;" Thread.sleep(1000); String queryString = "from Employee e where e.id > " + id; QueryStatistics queryStats = stats.getQueryStatistics(queryString); Query query = em.createQuery(queryString); query.setHint("org.hibernate.cacheable", true); // query - this call should fill the cache query.getResultList(); assertEquals( "Expected 1 miss in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheMissCount()); assertEquals( "Expected 1 put in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCachePutCount()); assertEquals( "Expected no hits in cache" + generateQueryCacheStats(queryStats), 0, queryStats.getCacheHitCount()); // query - second call should hit cache query.getResultList(); assertEquals( "Expected 1 hit in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheHitCount()); } catch (AssertionError e) { return e.getMessage(); } catch (InterruptedException e) { return e.getMessage(); } finally { em.close(); } return "OK"; }
@Transactional @Test public void test() throws SQLException { Pedido pedido = Pedido.newPedido(123); pedido.estadoPedido = EstadoPedido.PARCIALMENTE_FATURADO; entityManager.persist(pedido); @SuppressWarnings("deprecation") Connection connection = entityManager.unwrap(Session.class).connection(); PreparedStatement pst = connection.prepareStatement("select estado_pedido from Pedido where id = ?"); pst.setLong(1, pedido.getId()); ResultSet rs = pst.executeQuery(); assertTrue(rs.next()); String value = rs.getString(1); assertEquals("S", value); }
public void testSetup() { EntityManager em = createEntityManager(); // First clear old data from store. beginTransaction(em); KVStore store = ((OracleNoSQLConnection) em.unwrap(javax.resource.cci.Connection.class)).getStore(); Iterator<Key> iterator = store.storeKeysIterator(Direction.UNORDERED, 0); while (iterator.hasNext()) { store.multiDelete(iterator.next(), null, null); } commitTransaction(em); beginTransaction(em); try { for (int index = 0; index < 10; index++) { existingOrder = new Order(); existingOrder.id = this.nextId++; existingOrder.orderedBy = "ACME"; existingOrder.address = new Address(); existingOrder.address.city = "Ottawa"; existingOrder.address.addressee = "Bob Jones"; existingOrder.address.state = "CA"; existingOrder.address.country = "Mexico"; existingOrder.address.zipCode = "12345"; LineItem line = new LineItem(); line.itemName = "stuff"; line.itemPrice = new BigDecimal("10.99"); line.lineNumber = 1; line.quantity = 100; existingOrder.lineItems.add(line); line = new LineItem(); line.itemName = "more stuff"; line.itemPrice = new BigDecimal("20.99"); line.lineNumber = 2; line.quantity = 50; existingOrder.lineItems.add(line); existingOrder.comments.add("priority order"); existingOrder.comments.add("next day"); em.persist(existingOrder); } commitTransaction(em); } finally { closeEntityManagerAndTransaction(em); } clearCache(); }
/** Checking entity 2LC in one EntityManager session */ public String sameSessionCheck(String CACHE_REGION_NAME) { EntityManager em = emf.createEntityManager(); Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics(); stats.clear(); SecondLevelCacheStatistics emp2LCStats = stats.getSecondLevelCacheStatistics(CACHE_REGION_NAME + "Employee"); try { // add new entities and check if they are put in 2LC createEmployee(em, "Peter", "Ostrava", 2); createEmployee(em, "Tom", "Brno", 3); assertEquals( "There are 2 puts in the 2LC" + generateEntityCacheStats(emp2LCStats), 2, emp2LCStats.getPutCount()); // loading all Employee entities should put in 2LC all Employee List<?> empList = getAllEmployeesQuery(em); assertEquals("There are 2 entities.", empList.size(), 2); assertEquals( "There are 2 entities in the 2LC" + generateEntityCacheStats(emp2LCStats), 2, emp2LCStats.getElementCountInMemory()); // clear session em.clear(); // entity should be loaded from 2L cache, we'are expecting hit in 2L cache Employee emp = getEmployee(em, 2); assertNotNull("Employee returned", emp); assertEquals( "Expected 1 hit in cache" + generateEntityCacheStats(emp2LCStats), 1, emp2LCStats.getHitCount()); } catch (AssertionError e) { return e.getMessage(); } finally { em.close(); } return "OK"; }
public JasperPrint RelatorioDataLog(java.sql.Timestamp data1, java.sql.Timestamp data2) throws SQLException { JasperPrint rel = null; try { EntityManager em = new JPAUtil().getEntityManager(); Connection con = em.unwrap(java.sql.Connection.class); HashMap map = new HashMap(); map.put("DataInicio", data1); map.put("DataFinal", data2); InputStream resource = getClass().getResourceAsStream("LogDatas.jasper"); rel = JasperFillManager.fillReport(resource, map, con); System.out.println(data1.getTime()); } catch (JRException e) { JOptionPane.showMessageDialog(null, e.getMessage()); } return rel; }
@Test public void testListeners() throws Exception { File testPackage = buildExplicitPar(); addPackageToClasspath(testPackage); EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1", new HashMap()); EntityManager em = emf.createEntityManager(); EventListenerRegistry listenerRegistry = em.unwrap(SessionImplementor.class) .getFactory() .getServiceRegistry() .getService(EventListenerRegistry.class); assertEquals( "Explicit pre-insert event through hibernate.ejb.event.pre-insert does not work", listenerRegistry.getEventListenerGroup(EventType.PRE_INSERT).count(), listenerRegistry.getEventListenerGroup(EventType.PRE_UPDATE).count() + 1); em.close(); emf.close(); }
public List<CatMenuEntity> findMenuList(CatMenuSearchCriteria searchCriteria) { Session session = em.unwrap(Session.class); Criteria criteria = session.createCriteria(CatMenuEntity.class, "m"); if (searchCriteria.getFiscalYear() != null) { criteria.add(Restrictions.eq("m.fiscalYear.id", searchCriteria.getFiscalYear().getId())); } if (searchCriteria.getStartDate() != null) { criteria.add(Restrictions.ge("m.menuDate", searchCriteria.getStartDate())); } if (searchCriteria.getEndDate() != null) { criteria.add(Restrictions.le("m.menuDate", searchCriteria.getEndDate())); } criteria.addOrder(Order.asc("m.menuDate")); List<CatMenuEntity> resultList = criteria.list(); return resultList; }
@Path("deletetype/{typename}") @GET public XMLEntityMappings deleteType(@PathParam("typename") String typeName) throws Exception { List<Attribute<?, ?>> attrs = JpaMetamodelHelper.findReferringProps(typeName, true); if (!attrs.isEmpty()) { throw new CodedExceptionImpl( TYPE_REFERED, "Deletion can not be performed. Target type is referred by other types"); } EntityManager eManager = App.getEM(); eManager.getTransaction().begin(); Connection connection = eManager.unwrap(Connection.class); for (String sql : JpaHelper.deletePropDBStructure(eManager, typeName)) { LOGGER.info(sql); connection.createStatement().execute(sql); } eManager.getTransaction().commit(); JpaMapHelper.deleteClassAccessor(DynamicMetaSource.getEntityMaps(), typeName); App.getPersistenceUnit().refresh(false); mapPersister.save(DynamicMetaSource.getEntityMaps()); return DynamicMetaSource.getEntityMaps(); }
public void gerar() throws SQLException { String path = JPAUtil.getConfRelatorio(); System.out.println("End relat: " + path); EntityManager em = new JPAUtil().getEntityManager(); em.getTransaction().begin(); Session hibernateSession = em.unwrap(Session.class); hibernateSession.doWork( new org.hibernate.jdbc.Work() { @Override public void execute(Connection con) throws SQLException { try { HashMap map = new HashMap(); JasperPrint rel = JasperFillManager.fillReport(path + "Geral.jasper", map, con); JasperViewer jrviewer = new JasperViewer(rel, false); jrviewer.show(); } catch (JRException ex) { Logger.getLogger(RelatorioController.class.getName()).log(Level.SEVERE, null, ex); } } }); }
@Test public void testWrappedFromEntityManagerAPI() throws Exception { final EntityManagerFactory emf = Persistence.createEntityManagerFactory("ogm", TestHelper.getEnvironmentProperties()); assertThat(HibernateEntityManagerFactory.class.isAssignableFrom(emf.getClass())).isTrue(); SessionFactory factory = ((HibernateEntityManagerFactory) emf).getSessionFactory(); assertThat(factory.getClass()).isEqualTo(OgmSessionFactoryImpl.class); Session s = factory.openSession(); assertThat(s.getClass()).isEqualTo(OgmSessionImpl.class); assertThat(s.getSessionFactory().getClass()).isEqualTo(OgmSessionFactoryImpl.class); s.close(); EntityManager em = emf.createEntityManager(); assertThat(em.unwrap(Session.class) instanceof OgmSession); assertThat(em.getDelegate().getClass()).isEqualTo(OgmSessionImpl.class); em.close(); emf.close(); }