TransactionState(final String ctx) { this.startTime = System.currentTimeMillis(); this.txUuid = String.format("%s:%s", ctx, UUID.randomUUID().toString()); this.stopWatch = new StopWatch(); this.stopWatch.start(); this.owner = Logs.isExtrrreeeme() ? Threads.currentStackString() : "n/a"; try { this.eventLog(TxStep.BEGIN, TxEvent.CREATE); final EntityManagerFactory anemf = (EntityManagerFactoryImpl) PersistenceContexts.getEntityManagerFactory(ctx); checkParam(anemf, notNullValue()); this.em = anemf.createEntityManager(); checkParam(this.em, notNullValue()); this.transaction = this.em.getTransaction(); this.transaction.begin(); this.session = new WeakReference<Session>((Session) this.em.getDelegate()); this.eventLog(TxStep.END, TxEvent.CREATE); } catch (final Throwable ex) { Logs.exhaust().error(ex, ex); this.eventLog(TxStep.FAIL, TxEvent.CREATE); this.rollback(); throw new RuntimeException(PersistenceExceptions.throwFiltered(ex)); } finally { outstanding.put(this.txUuid, this); } }
/** * The merge method should copy all entity data into entity manager. Entity itself in not attached * nor persisted. */ @Test public void entityEquality_mergeInto_EntityManager() { // load and detach entity EntityManager em1 = factory.createEntityManager(); Person person1 = em1.find(Person.class, SIMON_SLASH_ID); em1.close(); // change its property person1.setFirstName("New Name"); // merge it into some entity manager EntityManager em2 = factory.createEntityManager(); em2.merge(person1); // this change will be ignored person1.setFirstName("Ignored Change"); Person person2 = em2.find(Person.class, SIMON_SLASH_ID); em2.close(); // entity itself was not attached assertNotSame(person1, person2); // however, its changed data was assertEquals("New Name", person2.getFirstName()); // changed data are NOT available in different entity manager EntityManager em3 = factory.createEntityManager(); Person person3 = em3.find(Person.class, SIMON_SLASH_ID); em3.close(); assertNotSame("New Name", person3.getFirstName()); }
@Test public void testCfgXmlPar() throws Exception { File testPackage = buildCfgXmlPar(); addPackageToClasspath(testPackage); EntityManagerFactory emf = Persistence.createEntityManagerFactory("cfgxmlpar", new HashMap()); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setDescr("Blah"); i.setName("factory"); Morito m = new Morito(); m.setPower("SuperStrong"); em.getTransaction().begin(); em.persist(i); em.persist(m); em.getTransaction().commit(); em.getTransaction().begin(); i = em.find(Item.class, i.getName()); em.remove(i); em.remove(em.find(Morito.class, m.getId())); em.getTransaction().commit(); em.close(); emf.close(); }
private void shutdown() { if (entityManager != null) { try { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } } finally { entityManager.close(); entityManager = null; } } if (entityManagerFactory != null) { entityManagerFactory.getCache().evictAll(); entityManagerFactory.close(); entityManagerFactory = null; } // clean shutdown of derby if (isDerby) { try { DriverManager.getConnection("jdbc:derby:;shutdown=true"); } catch (SQLException e) { if (!e.getMessage().equals("Derby system shutdown.")) { throw new RuntimeException(e); } } } }
/** * Get the EntityManager for the specified persistence unit name. * * @param name The persistence unit name */ public EntityManager em(String name) { EntityManagerFactory emf = emfs.get(name); if (emf == null) { return null; } return emf.createEntityManager(); }
public static void main(String[] args) { try { EntityManagerFactory f = Persistence.createEntityManagerFactory("DemoPU"); EntityManager manager = f.createEntityManager(); Scanner in = new Scanner(System.in); System.out.print("Enter id to modify"); int id = in.nextInt(); in.nextLine(); Emp e = manager.find(Emp.class, id); System.out.println("current details are"); System.out.println(e.getEname() + "\t" + e.getJob() + "\t" + e.getSalary()); System.out.println("Enter name to update"); String n = in.nextLine(); System.out.println("Enter job to update"); String j = in.nextLine(); System.out.println("Enter salary to update"); int s = in.nextInt(); EntityTransaction t = manager.getTransaction(); t.begin(); e.setEname(n); e.setJob(j); e.setSalary(s); t.commit(); manager.close(); System.out.println("updated"); } catch (Exception e) { System.out.println(e); } }
/** * Returns a list of dates from trade open until expiration. * * @param expiration * @return */ public static List<Date> getTradeDatesStarting(Date expiration, Date startDate) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAOptionsTrader"); EntityManager em = emf.createEntityManager(); // Note: table name refers to the Entity Class and is case sensitive // field names are property names in the Entity Class Query query = em.createQuery( "select distinct(opt.trade_date) from " + TradeProperties.SYMBOL_FOR_QUERY + " opt " + "where " + "opt.trade_date >= :tradeDate " + "opt.expiration=:expiration " // + "and opt.call_put = :call_put " // + "and opt.delta > 0.04 " // + "and opt.delta < 0.96 " + "order by opt.trade_date"); query.setParameter("tradeDate", startDate); query.setParameter("expiration", expiration); // query.setParameter("call_put", callPut); List<Date> dates = query.getResultList(); em.close(); return dates; }
private Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> createEntityManagers(BeanContext beanContext) { // create the extended entity managers Index<EntityManagerFactory, Map> factories = beanContext.getExtendedEntityManagerFactories(); Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> entityManagers = null; if (factories != null && factories.size() > 0) { entityManagers = new Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker>( new ArrayList<EntityManagerFactory>(factories.keySet())); for (Map.Entry<EntityManagerFactory, Map> entry : factories.entrySet()) { EntityManagerFactory entityManagerFactory = entry.getKey(); Map properties = entry.getValue(); JtaEntityManagerRegistry.EntityManagerTracker entityManagerTracker = entityManagerRegistry.getInheritedEntityManager(entityManagerFactory); EntityManager entityManager; if (entityManagerTracker == null) { if (properties != null) { entityManager = entityManagerFactory.createEntityManager(properties); } else { entityManager = entityManagerFactory.createEntityManager(); } entityManagerTracker = new JtaEntityManagerRegistry.EntityManagerTracker(entityManager); } else { entityManagerTracker.incCounter(); } entityManagers.put(entityManagerFactory, entityManagerTracker); } } return entityManagers; }
// EXCLUI UM CAIXA @Override public void excluir(Caixa caixa) throws PersistenceException { EntityManagerFactory conexao = Persistence.createEntityManagerFactory("MDJPapeisPU"); try { EntityManager entityManager = conexao.createEntityManager(); entityManager.getTransaction().begin(); // Tornando o caixa gerenciável pelo entityManager, necessário para usar o método remove a // seguir caixa = entityManager.find(Caixa.class, caixa.getCodigo()); entityManager.remove(caixa); entityManager.getTransaction().commit(); entityManager.close(); } catch (IllegalArgumentException ex) { System.out.println("CaixaDAO - CATCH IllegalArgumentException"); ex.printStackTrace(); throw new PersistenceException(ex); } catch (PersistenceException ex) { System.out.println("CaixaDAO - CATCH PersistenceException"); ex.printStackTrace(); throw new PersistenceException(ex); } finally { conexao.close(); } }
@Test public void deveriaSeConectarComOBancoDeDados() throws Exception { EntityManagerFactory factory = Persistence.createEntityManagerFactory("default"); EntityManager entityManager = factory.createEntityManager(); assertNotNull(entityManager); }
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); // Obtain a database connection: EntityManagerFactory emf = (EntityManagerFactory) getServletContext().getAttribute("emf"); EntityManager em = emf.createEntityManager(); try { // Handle a new guest (if any): String name = request.getParameter("name"); if (name != null) { em.getTransaction().begin(); em.persist(new memberController(name)); em.getTransaction().commit(); } // Display the list of guests: List<member> memberList = em.createQuery("SELECT m FROM member m").getResultList(); request.setAttribute("member", memberList); request.getRequestDispatcher("/daftarmember.jsp").forward(request, response); } finally { // Close the database connection: if (em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); } }
/** 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"; }
/** @param args */ public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("withoutcreate"); EntityManager manager = factory.createEntityManager(); N1Select test = new N1Select(manager); TypedQuery<Department> q = test.manager.createQuery("select d from Department d", Department.class); long start = System.currentTimeMillis(); List<Department> res = q.getResultList(); for (Department d : res) { for (Employee e : d.getEmployees()) { e.getName(); } } long end = System.currentTimeMillis(); long duree = end - start; System.err.println("temps d'exec = " + duree); // TODO persist entity // TODO run request System.out.println(".. done"); }
@Test public void testCreateThenDrop() throws Exception { URL persistenceXmlUrl = Thread.currentThread().getContextClassLoader().getResource(PERSISTENCE_XML_RESOURCE_NAME); if (persistenceXmlUrl == null) { persistenceXmlUrl = Thread.currentThread() .getContextClassLoader() .getResource('/' + PERSISTENCE_XML_RESOURCE_NAME); } assertNotNull(persistenceXmlUrl); ParsedPersistenceXmlDescriptor persistenceUnit = PersistenceXmlParser.locateIndividualPersistenceUnit(persistenceXmlUrl); // creating the EMF causes SchemaCreator to be run... EntityManagerFactory emf = Bootstrap.getEntityManagerFactoryBuilder(persistenceUnit, Collections.emptyMap()).build(); // closing the EMF causes the delayed SchemaDropper to be run... // wrap in a transaction just to see if we can get this to fail in the way the WF report says; // in my experience however this succeeds with or without the transaction final TransactionManager tm = emf.unwrap(SessionFactoryImplementor.class) .getServiceRegistry() .getService(JtaPlatform.class) .retrieveTransactionManager(); tm.begin(); Transaction txn = tm.getTransaction(); emf.close(); txn.commit(); }
public static void main(String[] args) { EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("JPA"); EntityManager entitymanager = emfactory.createEntityManager(); entitymanager.getTransaction().begin(); // Teaching staff entity TeachingStaff ts1 = new TeachingStaff(1, "Gopal", "MSc MEd", "Maths"); TeachingStaff ts2 = new TeachingStaff(2, "Manisha", "BSc BEd", "English"); // Non-Teaching Staff entity NonTeachingStaff nts1 = new NonTeachingStaff(3, "Satish", "Accounts"); NonTeachingStaff nts2 = new NonTeachingStaff(4, "Krishna", "Office Admin"); // storing all entities entitymanager.persist(ts1); entitymanager.persist(ts2); entitymanager.persist(nts1); entitymanager.persist(nts2); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); List<entities.Course> courses = new ArrayList<entities.Course>(); if (session.getAttribute("courses_validated_list") == null) { // 1 Create the factory of Entity Manager EntityManagerFactory factory = Persistence.createEntityManagerFactory("PersistenceJPAProject"); // 2 Create the Entity Manager EntityManager em = factory.createEntityManager(); // 3 Get one EntityTransaction and start it EntityTransaction tx = em.getTransaction(); tx.begin(); try { courses = em.createNamedQuery("Course.findValidatedCourses", entities.Course.class) .getResultList(); } catch (NoResultException e) { courses = null; } session.setAttribute("courses_validated_list", courses); tx.commit(); em.close(); } ((HttpServletResponse) response).sendRedirect("CoursesList.jsp"); }
public static void main(String[] args) throws Exception { System.out.println("hello from Customer.java"); EntityManagerFactory factory = Persistence.createEntityManagerFactory("customerPU"); EntityManager manager = factory.createEntityManager(); Query q1 = manager.createQuery("SELECT COUNT(c) FROM Customer c"); Long count = (Long) q1.getSingleResult(); if (count == 0) { // record is empty, read from data.txst System.out.println("record empty, read from data.txt..."); // try { FileReader fr = new FileReader("data.txt"); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { // System.out.println(s); // split the string s Object[] items = s.split("\\|"); // store in string list // List<String> itemList= new ArrayList<String>(Arrays.asList(items)); // string list converted to array // Object[] itemArray = itemList.toArray(); // insert data into database table manager.getTransaction().begin(); Customer c = new Customer(); // add email c.setEmail((String) items[0]); // add pass c.setPass((String) items[1]); // add name c.setName((String) items[2]); // add address c.setAddress((String) items[3]); // add yob c.setYob((String) items[4]); // change to managed state manager.persist(c); manager.getTransaction().commit(); } fr.close(); } // display the records Query q2 = manager.createNamedQuery("Customer.findAll"); List<Customer> customers = q2.getResultList(); for (Customer c : customers) { System.out.println(c.getName() + ", " + c.getEmail()); } manager.close(); factory.close(); }
private static void insereIteracao(Pendencia pendencia) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("hemoproject"); EntityManager manager = factory.createEntityManager(); manager.getTransaction().begin(); UserDAO usuariodao = new UserDAO(); // obtem o usuário usuariodao.beginTransaction(); User usuario = usuariodao.findUserByMasp("@Importacao"); usuariodao.closeTransaction(); Iteracao iteracao = new Iteracao(); // iteracao.setCategoria(Categoria.CONFIGURACAO); iteracao.setDescricao("Pendente de validação do usuário. Conforme e-mail enviado."); iteracao.setStatus(Status.PENDENTE_USUARIO); iteracao.setUsuario(usuario); iteracao.setPendencia(pendencia); iteracao.setDataDaPendencia(new GregorianCalendar().getInstance()); manager.persist(iteracao); manager.getTransaction().commit(); manager.close(); factory.close(); System.out.println("gravou"); }
public void remover(Integer id) throws Exception { EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAW-Trabalho-ModelPU"); EntityManager em = emf.createEntityManager(); try { if (em.getTransaction().isActive() == false) { em.getTransaction().begin(); } Venda objeto = em.find(Venda.class, id); em.remove(objeto); em.getTransaction().commit(); } catch (Exception e) { if (em.getTransaction().isActive() == false) { em.getTransaction().begin(); } em.getTransaction().rollback(); throw new Exception("Erro ao executar a operação de persistência:" + e.getMessage()); } finally { em.close(); emf.close(); } }
/** This method creates a entity manager. */ private EntityManager getEntityManager(KieRuntimeEvent event) { Environment env = event.getKieRuntime().getEnvironment(); /** * It's important to set the sharedEM flag with _every_ operation otherwise, there are * situations where: 1. it can be set to "true" 2. something can happen 3. the "true" value can * no longer apply (I've seen this in debugging logs.. ) */ sharedEM = false; if (emf != null) { return emf.createEntityManager(); } else if (env != null) { EntityManager em = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER); if (em != null) { sharedEM = true; return em; } EntityManagerFactory emf = (EntityManagerFactory) env.get(EnvironmentName.ENTITY_MANAGER_FACTORY); if (emf != null) { return emf.createEntityManager(); } } throw new RuntimeException("Could not find or create a new EntityManager!"); }
/** * This method should be called in the @After method of a test to clean up the persistence unit * and datasource. * * @param context A HashMap generated by {@link org.drools.persistence.util.PersistenceUtil * setupWithPoolingDataSource(String)} */ public static void cleanUp(HashMap<String, Object> context) { if (context != null) { BitronixTransactionManager txm = TransactionManagerServices.getTransactionManager(); if (txm != null) { txm.shutdown(); } Object emfObject = context.remove(ENTITY_MANAGER_FACTORY); if (emfObject != null) { try { EntityManagerFactory emf = (EntityManagerFactory) emfObject; emf.close(); } catch (Throwable t) { t.printStackTrace(); } } Object ds1Object = context.remove(DATASOURCE); if (ds1Object != null) { try { PoolingDataSource ds1 = (PoolingDataSource) ds1Object; ds1.close(); } catch (Throwable t) { t.printStackTrace(); } } } }
public static void main(String[] args) { double inicio = System.currentTimeMillis(); Conta conta = new Conta(); conta.setTitular("Armando da Silva"); conta.setBanco("Banco do Brasil"); conta.setAgencia("0316"); conta.setNumero("54321"); conta.setSaldo(new BigDecimal(1234.48)); /** Usando HSQLDB */ // EntityManagerFactory emf = Persistence // .createEntityManagerFactory("contas-hsqldb"); /** Usando PostgreSQL */ EntityManagerFactory emf = Persistence.createEntityManagerFactory("contas-postgres"); /* EntityManagerFactory emf = Persistence .createEntityManagerFactory("contasmysql"); */ EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(conta); em.getTransaction().commit(); em.close(); double fim = System.currentTimeMillis(); System.out.println("Executado em: " + (fim - inicio) / 1000 + "s"); }
public void testIllegalStateExceptionOnClosedEntityManagerFactory() { EntityManagerFactory emf = null; Metamodel metamodel = null; boolean exceptionThrown = false; try { emf = initialize(); // Verify an ISE if the emf is closed emf.close(); closeEntityManagerFactory(PERSISTENCE_UNIT_NAME); try { metamodel = emf.getMetamodel(); } catch (IllegalStateException e) { exceptionThrown = true; assertNull(metamodel); assertTrue(e instanceof IllegalStateException); // System.out.println("_Disclaimer: The above IllegalStateException is expected as part of // testing."); // e.printStackTrace(); } assertTrue(exceptionThrown); } catch (Exception e) { e.printStackTrace(); } }
@BeforeClass public static void getDAO() throws Exception { flightDao = new FlightDao(); EntityManagerFactory factory = Persistence.createEntityManagerFactory("BookingOfficeTest"); EntityManager entityManager = factory.createEntityManager(); flightDao.setEntityManager(entityManager); }
/** * Refresh method test loads an entity with two different entity managers. One updates the entity * and another refreshes it. The test checks whether refreshed entity contains changes. */ @Test public void entityEquality_refresh_EntityManager() { // load an entity EntityManager emRefresh = factory.createEntityManager(); Person person1 = emRefresh.find(Person.class, SIMON_SLASH_ID); // load the same entity by different entity manager EntityManager emChange = factory.createEntityManager(); Person person2 = emChange.find(Person.class, SIMON_SLASH_ID); // change the first entity - second entity remains the same emRefresh.getTransaction().begin(); person1.setFirstName("refreshDemo"); assertNotSame("refreshDemo", person2.getFirstName()); // commit the transaction - second entity still remains the same emRefresh.getTransaction().commit(); assertNotSame("refreshDemo", person2.getFirstName()); // refresh second entity - it changes emChange.refresh(person2); assertEquals("refreshDemo", person2.getFirstName()); emRefresh.close(); emChange.close(); }
// TODO: Add a way to see details of a file public static UserFile getUserFileDataFromDb(Long userFileId) { EntityManagerFactory emf = Activator.getEmf(); EntityManager em = emf.createEntityManager(); UserFile userFile = em.find(UserFile.class, userFileId); return userFile; }
@Test public void testExcludeHbmPar() throws Exception { File testPackage = buildExcludeHbmPar(); addPackageToClasspath(testPackage); EntityManagerFactory emf = null; try { emf = Persistence.createEntityManagerFactory("excludehbmpar", new HashMap()); } catch (PersistenceException e) { Throwable nested = e.getCause(); if (nested == null) { throw e; } nested = nested.getCause(); if (nested == null) { throw e; } if (!(nested instanceof ClassNotFoundException)) { throw e; } fail("Try to process hbm file: " + e.getMessage()); } EntityManager em = emf.createEntityManager(); Caipirinha s = new Caipirinha("Strong"); em.getTransaction().begin(); em.persist(s); em.getTransaction().commit(); em.getTransaction().begin(); s = em.find(Caipirinha.class, s.getId()); em.remove(s); em.getTransaction().commit(); em.close(); emf.close(); }
public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("TA-FINAL-PU"); EntityManager em = emf.createEntityManager(); Filme f = new Filme(); Filme ff = em.find(Filme.class, 42); Cinema c = new Cinema(); Cinema cc = em.find(Cinema.class, 2); Sessao obj = new Sessao(); obj.setData(Calendar.getInstance()); obj.setHora("16h as 18h"); obj.setValorInteiro(28.00); obj.setValorMeia(14.00); obj.setNumSala("25b"); obj.setCinema(cc); obj.setFilme(ff); em.getTransaction().begin(); em.persist(obj); em.getTransaction().commit(); em.close(); emf.close(); }
@Test public void testDefaultPar() throws Exception { File testPackage = buildDefaultPar(); addPackageToClasspath(testPackage); // run the test EntityManagerFactory emf = Persistence.createEntityManagerFactory("defaultpar", new HashMap()); EntityManager em = emf.createEntityManager(); ApplicationServer as = new ApplicationServer(); as.setName("JBoss AS"); Version v = new Version(); v.setMajor(4); v.setMinor(0); v.setMicro(3); as.setVersion(v); Mouse mouse = new Mouse(); mouse.setName("mickey"); em.getTransaction().begin(); em.persist(as); em.persist(mouse); assertEquals(1, em.createNamedQuery("allMouse").getResultList().size()); Lighter lighter = new Lighter(); lighter.name = "main"; lighter.power = " 250 W"; em.persist(lighter); em.flush(); em.remove(lighter); em.remove(mouse); assertNotNull(as.getId()); em.remove(as); em.getTransaction().commit(); em.close(); emf.close(); }
@BeforeClass public static void setUpClass() throws Exception { EntityManagerFactory emf = Persistence.createEntityManagerFactory("BOMPU"); em = emf.createEntityManager(); repository = RepositoryFactory.getRepositoryOf(Produs.class); logger.info("setUpClass runned"); }