List of usage examples for javax.persistence EntityManager close
public void close();
From source file:fredboat.db.entity.SearchResult.java
/** * Persist a search in the database.//from w ww.j a v a 2s . com * * @return the merged SearchResult object */ public SearchResult save() { DatabaseManager dbManager = FredBoat.getDbManager(); if (dbManager == null || !dbManager.isAvailable()) { throw new DatabaseNotReadyException(); } EntityManager em = dbManager.getEntityManager(); try { em.getTransaction().begin(); SearchResult managed = em.merge(this); em.getTransaction().commit(); return managed; } catch (PersistenceException e) { log.error("Unexpected error while saving a search result for provider {} and search term {}", searchResultId.provider, searchResultId.searchTerm, e); throw new DatabaseNotReadyException(e); } finally { em.close(); } }
From source file:org.drools.container.spring.beans.persistence.VariablePersistenceStrategyTest.java
@Test public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException { MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields"); MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods"); MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields( "This is a test Entity with annotations in fields and without accesors methods"); MyVariableSerializable myVariableSerializable = new MyVariableSerializable( "This is a test SerializableObject"); EntityManager em = ((EntityManagerFactory) ctx.getBean("myEmf")).createEntityManager(); em.getTransaction().begin();/*from w w w. j ava 2 s. c o m*/ em.persist(myEntity); em.persist(myEntityMethods); em.persist(myEntityOnlyFields); em.getTransaction().commit(); em.close(); log.info("---> get bean jpaSingleSessionCommandService"); StatefulKnowledgeSession service = (StatefulKnowledgeSession) ctx.getBean("jpaSingleSessionCommandService"); int sessionId = service.getId(); log.info("---> created SingleSessionCommandService id: " + sessionId); log.info("### Starting process ###"); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("x", "SomeString"); parameters.put("y", myEntity); parameters.put("m", myEntityMethods); parameters.put("f", myEntityOnlyFields); parameters.put("z", myVariableSerializable); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) service .startProcess("com.sample.ruleflow", parameters); log.info("Started process instance {}", processInstance.getId()); TestWorkItemHandler handler = TestWorkItemHandler.getInstance(); WorkItem workItem = handler.getWorkItem(); assertNotNull(workItem); service.dispose(); EntityManagerFactory emf = (EntityManagerFactory) ctx.getBean("myEmf"); // List< ? > result = emf.createEntityManager().createQuery( "select i from VariableInstanceInfo i" ).getResultList(); // assertEquals( 5, // result.size() ); log.info("### Retrieving process instance ###"); Environment env = KnowledgeBaseFactory.newEnvironment(); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf); env.set(EnvironmentName.TRANSACTION_MANAGER, ctx.getBean("txManager")); env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[] { // new JPAPlaceholderResolverStrategy(env), new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT) }); KnowledgeStoreService kstore = (KnowledgeStoreService) ctx.getBean("kstore1"); KnowledgeBase kbase1 = (KnowledgeBase) ctx.getBean("kbase1"); service = kstore.loadStatefulKnowledgeSession(sessionId, kbase1, null, env); processInstance = (WorkflowProcessInstance) service.getProcessInstance(processInstance.getId()); assertNotNull(processInstance); assertNotNull(processInstance); assertEquals("SomeString", processInstance.getVariable("x")); assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest()); assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest()); assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test); assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText()); assertNull(processInstance.getVariable("a")); assertNull(processInstance.getVariable("b")); assertNull(processInstance.getVariable("c")); service.dispose(); // log.info("### Completing first work item ###"); // ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null ); // // workItem = handler.getWorkItem(); // assertNotNull( workItem ); // // log.info("### Retrieving variable instance infos ###"); // result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList(); // assertEquals(8, result.size()); // for (Object o: result) { // assertTrue(VariableInstanceInfo.class.isAssignableFrom(o.getClass())); // log.info(o); // } // // log.info("### Retrieving process instance ###"); // ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env); // processInstance = (WorkflowProcessInstance) // ksession.getProcessInstance(processInstance.getId()); // assertNotNull(processInstance); // assertEquals("SomeString", processInstance.getVariable("x")); // assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest()); // assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest()); // assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test); // assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText()); // assertEquals("Some new String", processInstance.getVariable("a")); // assertEquals("This is a new test Entity", ((MyEntity) processInstance.getVariable("b")).getTest()); // assertEquals("This is a new test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText()); // log.info("### Completing second work item ###"); // ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null); // // workItem = handler.getWorkItem(); // assertNotNull(workItem); // // result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList(); // assertEquals(8, result.size()); // // log.info("### Retrieving process instance ###"); // ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env); // processInstance = (WorkflowProcessInstance) // ksession.getProcessInstance(processInstance.getId()); // assertNotNull(processInstance); // assertEquals("SomeString", processInstance.getVariable("x")); // assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest()); // assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest()); // assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test); // assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText()); // assertEquals("Some changed String", processInstance.getVariable("a")); // assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest()); // assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText()); // log.info("### Completing third work item ###"); // ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null); // // workItem = handler.getWorkItem(); // assertNull(workItem); // // result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList(); // //This was 6.. but I change it to 0 because all the variables will go away with the process instance.. // //we need to change that to leave the variables there??? // assertEquals(0, result.size()); // // ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env); // processInstance = (WorkflowProcessInstance) // ksession.getProcessInstance(processInstance.getId()); // assertNull(processInstance); }
From source file:com.epam.training.taranovski.web.project.repository.implementation.CheckDocumentRepositoryImplementation.java
@Override public CheckDocument findByVacancy(Vacancy vacancy) { EntityManager em = entityManagerFactory.createEntityManager(); CheckDocument checkDocument = null;//w w w .j a v a2s . co m try { em.getTransaction().begin(); TypedQuery<CheckDocument> query = em.createNamedQuery("CheckDocument.findByVacancy", CheckDocument.class); query.setParameter("vacancy", vacancy); checkDocument = query.getSingleResult(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return checkDocument; }
From source file:org.noorganization.instalist.server.api.EntryResource.java
/** * Deletes the entry.// ww w .ja va 2 s .c o m * @param _groupId The id of the group containing the entry. * @param _entryUUID The uuid of the entry itself. */ @DELETE @TokenSecured @Path("{entryuuid}") @Produces({ "application/json" }) public Response deleteListEntryById(@PathParam("groupid") int _groupId, @PathParam("entryuuid") String _entryUUID) throws Exception { UUID toDelete; try { toDelete = UUID.fromString(_entryUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); IEntryController entryController = ControllerFactory.getEntryController(manager); try { entryController.delete(_groupId, toDelete); } catch (NotFoundException _e) { return ResponseFactory.generateNotFound(new Error().withMessage("The entry was not " + "found.")); } catch (GoneException _e) { return ResponseFactory.generateGone(new Error().withMessage("The entry has been " + "deleted.")); } finally { manager.close(); } return ResponseFactory.generateOK(null); }
From source file:com.epam.training.taranovski.web.project.repository.implementation.CheckDocumentRepositoryImplementation.java
@Override public CheckDocument findByEmployee(Employee employee) { EntityManager em = entityManagerFactory.createEntityManager(); CheckDocument checkDocument = null;/*from w w w. j a v a 2 s . c om*/ try { em.getTransaction().begin(); TypedQuery<CheckDocument> query = em.createNamedQuery("CheckDocument.findByEmployee", CheckDocument.class); query.setParameter("employee", employee); checkDocument = query.getSingleResult(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return checkDocument; }
From source file:com.epam.training.taranovski.web.project.repository.implementation.CheckDocumentRepositoryImplementation.java
@Override public List<CheckDocument> findAllForEmployer(Employer employer) { EntityManager em = entityManagerFactory.createEntityManager(); List<CheckDocument> list = new LinkedList<>(); try {/*from w ww.j a va 2 s . c om*/ em.getTransaction().begin(); TypedQuery<CheckDocument> query = em.createNamedQuery("CheckDocument.findAllForEmployer", CheckDocument.class); query.setParameter("employer", employer); list = query.getResultList(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return list; }
From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java
@Override public boolean delete(Vacancy vacancy) { EntityManager em = entityManagerFactory.createEntityManager(); boolean success = true; Vacancy managedVacancy = null;//from w ww . java2 s. c o m try { em.getTransaction().begin(); managedVacancy = em.merge(vacancy); em.remove(managedVacancy); em.getTransaction().commit(); success = true; } catch (RuntimeException e) { Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); success = false; } em.close(); } return success; }
From source file:fr.univlorraine.ecandidat.controllers.DemoController.java
/** Lance un script sql * @param script/*from w w w . jav a2s . co m*/ */ @Transactional private void launchSqlScript(String script) { EntityManager em = entityManagerFactoryEcandidat.createEntityManager(); em.getTransaction().begin(); try { final InputStream inputStream = this.getClass().getResourceAsStream("/db/demo/" + script); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader bufferedReader = new BufferedReader(inputStreamReader); while (bufferedReader.ready()) { Query query = em.createNativeQuery(bufferedReader.readLine()); query.executeUpdate(); } } catch (Exception e) { em.getTransaction().rollback(); em.close(); } em.getTransaction().commit(); em.close(); }
From source file:org.noorganization.instalist.server.api.UnitResource.java
/** * Deletes the unit./*w w w .j ava 2 s . c o m*/ * @param _groupId The groups id containing the existing unit. * @param _unitUUID The uuid of the unit to delete. */ @DELETE @TokenSecured @Path("{unituuid}") @Produces({ "application/json" }) public Response deleteUnit(@PathParam("groupid") int _groupId, @PathParam("unituuid") String _unitUUID) throws Exception { UUID toDelete; try { toDelete = UUID.fromString(_unitUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); IUnitController unitController = ControllerFactory.getUnitController(manager); try { unitController.delete(_groupId, toDelete); } catch (NotFoundException _e) { return ResponseFactory.generateNotFound(new Error().withMessage("The unit was not " + "found.")); } catch (GoneException _e) { return ResponseFactory .generateGone(new Error().withMessage("The unit has been " + "already deleted before.")); } finally { manager.close(); } return ResponseFactory.generateOK(null); }
From source file:de.zib.gndms.infra.tests.FileTransferActionTest.java
@Test(groups = { "net", "db", "sys", "action", "task" }) public void testIt() throws ResourceException, ExecutionException, InterruptedException { EntityManager em = null; try {/*from w w w . ja va 2 s.c o m*/ em = getSys().getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); em.persist(task); em.getTransaction().commit(); FileTransferTaskAction action = new FileTransferTaskAction(em, task); Future<AbstractTask> serializableFuture = getSys().submitAction(action, log); assert serializableFuture.get().getState().equals(TaskState.FINISHED); FileTransferResult ftr = (FileTransferResult) task.getData(); for (String s : Arrays.asList(ftr.getFiles())) System.out.println(s); } finally { if (em != null && em.isOpen()) em.close(); } }