List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:fredboat.db.entity.SearchResult.java
/** * Persist a search in the database.//w w w.j a v a2 s.co m * * @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:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java
@FXML private void cmdUpdateSET(ActionEvent event) { Task taskUpdateSET = new Task<Void>() { @Override//from w ww . j a v a 2 s. com public Void call() { try { EntityManager entityManager = Utils.getInstance().getEntityManagerFactory() .createEntityManager(); entityManager.getTransaction().begin(); String temp = ""; Integer count = 0; entityManager.createQuery("delete from TblContribuyentes t").executeUpdate(); for (Integer i = 0; i <= 9; i++) { URL url = new URL( "http://www.set.gov.py/rest/contents/download/collaboration/sites/PARAGUAY-SET/documents/informes-periodicos/ruc/ruc" + String.valueOf(i) + ".zip"); ZipInputStream zipStream = new ZipInputStream(url.openStream(), StandardCharsets.UTF_8); zipStream.getNextEntry(); Scanner sc = new Scanner(zipStream, "UTF-8"); while (sc.hasNextLine()) { String[] ruc = sc.nextLine().split("\\|"); temp = ruc[0] + " - " + ruc[1] + " - " + ruc[2]; if (ruc[0].length() > 0 && ruc[1].length() > 0 && ruc[2].length() == 1) { TblContribuyentes c = new TblContribuyentes(); c.setRucSinDv(ruc[0]); c.setRazonSocial(StringEscapeUtils.escapeSql(ruc[1])); c.setDv(ruc[2]); entityManager.persist(c); updateMessage("Descargando listado de RUC con terminacion " + String.valueOf(i) + " - Cantidad de contribuyentes procesada: " + String.format("%,d", count) + " de aprox. 850.000."); count++; } else { updateMessage(temp); } } entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); } updateMessage("Lista de RUC actualizada..."); return null; } catch (Exception ex) { App.showException(this.getClass().getName(), ex.getMessage(), ex); } return null; } }; lblUpdateSET.textProperty().bind(taskUpdateSET.messageProperty()); new Thread(taskUpdateSET).start(); }
From source file:com.doculibre.constellio.wicket.panels.admin.stats.CollectionStatsPanel.java
public CollectionStatsPanel(String id, final String collectionName) { super(id);//from w w w .ja v a2 s.c om endDate = new Date(); startDate = DateUtils.addMonths(endDate, -1); Form form = new Form("form") { @Override protected void onSubmit() { statsPanel.replaceWith(statsPanel = new CollectionStatsReportPanel(statsPanel.getId(), collectionName, statsType, startDate, endDate, rows, includeFederatedCollections)); } }; add(form); IModel queryExcludeRegexpsModel = new Model() { @Override public Object getObject() { String result; AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = adminCollectionPanel.getCollection(); CollectionStatsFilter statsFilter = collection.getStatsFilter(); if (statsFilter != null) { StringBuffer sb = new StringBuffer(); Set<String> existingRegexps = statsFilter.getQueryExcludeRegexps(); for (String existingRegexp : existingRegexps) { sb.append(existingRegexp); sb.append("\n"); } result = sb.toString(); } else { result = null; } return result; } @Override public void setObject(Object object) { String queryExcludeRegexpsStr = (String) object; String[] newRegexpsArray = StringUtils.split(queryExcludeRegexpsStr, "\n"); List<String> newRegexps = new ArrayList<String>(); for (String newRegexp : newRegexpsArray) { newRegexps.add(newRegexp.trim()); } AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = adminCollectionPanel.getCollection(); CollectionStatsFilter statsFilter = collection.getStatsFilter(); if (statsFilter == null) { statsFilter = new CollectionStatsFilter(); statsFilter.setRecordCollection(collection); collection.setStatsFilter(statsFilter); } Set<String> existingRegexps = statsFilter.getQueryExcludeRegexps(); if (!CollectionUtils.isEqualCollection(existingRegexps, newRegexps)) { RecordCollectionServices collectionServices = ConstellioSpringUtils .getRecordCollectionServices(); EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager(); if (!entityManager.getTransaction().isActive()) { entityManager.getTransaction().begin(); } existingRegexps.clear(); existingRegexps.addAll(newRegexps); collectionServices.makePersistent(collection, false); entityManager.getTransaction().commit(); } } }; form.add(new TextArea("queryExcludeRegexps", queryExcludeRegexpsModel)); form.add(new DateTextField("startDate", new PropertyModel(this, "startDate"), "yyyy-MM-dd") .add(new DatePicker())); form.add(new DateTextField("endDate", new PropertyModel(this, "endDate"), "yyyy-MM-dd") .add(new DatePicker())); form.add(new TextField("rows", new PropertyModel(this, "rows"), Integer.class)); form.add(new CheckBox("includeFederatedCollections", new PropertyModel(this, "includeFederatedCollections")) { @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = adminCollectionPanel.getCollection(); visible = collection.isFederationOwner(); } return visible ? visible : false; } }); form.add(new DropDownChoice("statsType", new PropertyModel(this, "statsType"), StatsConstants.ALL_STATS, new StringResourceChoiceRenderer("statsType", this))); form.add(new Label("title", new PropertyModel(this, "statsType"))); statsPanel = new AjaxLazyLoadPanel("statsPanel") { @Override public Component getLazyLoadComponent(String markupId) { return new CollectionStatsReportPanel(markupId, collectionName, statsType, startDate, endDate, rows, includeFederatedCollections); } }; form.add(statsPanel); }
From source file:cz.fi.muni.pa165.dto.PrintedBookDAOTest.java
@Test public void testUpdate() { EntityManager em = emf.createEntityManager(); PrintedBookDAOImpl bdao = new PrintedBookDAOImpl(); bdao.setManager(em);//from ww w . j a v a 2 s. c o m em.getTransaction().begin(); Book book = new Book(); book.setName("Harry Potter"); book.setISBN("123112315"); book.setDescription("Book about Wizard!"); book.setAuthors("J.K. Rowling"); book.setDepartment(Department.Sport); book.setIdBook(1); PrintedBook pbook = new PrintedBook(); pbook.setBook(book); pbook.setState(Boolean.FALSE); pbook.setCondition(Condition.New); pbook.setIdPrintedBook(2); bdao.update(pbook); PrintedBook b1 = bdao.find(pbook); em.getTransaction().commit(); em.close(); assertEquals(b1.getState(), Boolean.FALSE); }
From source file:cz.fi.muni.pa165.dto.PrintedBookDAOTest.java
@Test public void testDelete() { EntityManager em = emf.createEntityManager(); PrintedBookDAOImpl bdao = new PrintedBookDAOImpl(); bdao.setManager(em);/* www. ja v a 2 s . c o m*/ em.getTransaction().begin(); Book book = new Book(); book.setName("Harry Potter"); book.setISBN("123112315"); book.setDescription("Book about Wizard!"); book.setAuthors("J.K. Rowling"); book.setDepartment(Department.Sport); book.setIdBook(1); PrintedBook pbook = new PrintedBook(); pbook.setBook(book); pbook.setState(Boolean.FALSE); pbook.setCondition(Condition.New); pbook.setIdPrintedBook(1); bdao.delete(pbook); em.getTransaction().commit(); List<PrintedBook> books = em.createQuery("SELECT b FROM PrintedBook b", PrintedBook.class).getResultList(); em.close(); assertEquals(books.size(), 1); }
From source file:cz.fi.muni.pa165.dto.PrintedBookDAOTest.java
@Test public void testInsert() { EntityManager em = emf.createEntityManager(); PrintedBookDAOImpl bdao = new PrintedBookDAOImpl(); bdao.setManager(em);//from w w w .j a v a 2 s . c o m em.getTransaction().begin(); Book book = new Book(); book.setName("Harry Potter"); book.setISBN("123112315"); book.setDescription("Book about Wizard!"); book.setAuthors("J.K. Rowling"); book.setDepartment(Department.Sport); book.setIdBook(1); PrintedBook pbook = new PrintedBook(); pbook.setBook(book); pbook.setState(Boolean.FALSE); pbook.setCondition(Condition.Damaged); bdao.insert(pbook); em.getTransaction().commit(); List<PrintedBook> books = em.createQuery("SELECT b FROM PrintedBook b", PrintedBook.class).getResultList(); em.close(); assertEquals(books.size(), 3); }
From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java
@Override public List<Employee> getAppropriateAvailableEmployees(Vacancy vacancy) { EntityManager em = entityManagerFactory.createEntityManager(); List<Integer> list = null; List<Employee> list1 = new LinkedList<>(); try {/*from w ww .j a va 2 s . c o m*/ em.getTransaction().begin(); Query query = em.createNativeQuery( "select \"employeeId\" from (select \"employeeId\", \"vacancyId\" as \"ide\", count(*) as cou from (select \"UserSkill\".\"employeeId\", \"VacancySkill\".\"vacancyId\", \"UserSkill\".\"experience\", \"VacancySkill\".\"experience\" from \"UserSkill\" join \"VacancySkill\" on \"UserSkill\".\"allSkillsId\" = \"VacancySkill\".\"allSkillsId\" where \"UserSkill\".\"experience\" >= \"VacancySkill\".\"experience\" and \"VacancySkill\".\"vacancyId\" = ?) group by \"employeeId\", \"vacancyId\") where cou = (select count(*) from \"VacancySkill\" where \"VacancySkill\".\"vacancyId\" = \"ide\")"); query.setParameter(1, vacancy.getVacancyId()); list = query.getResultList(); if (list.isEmpty()) { list.add(0); } TypedQuery<Employee> query1 = em.createNamedQuery("Employee.findAmongIdsFreeEmployees", Employee.class); query1.setParameter("employeeIdList", list); list1 = query1.getResultList(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return list1; }
From source file:it.infn.ct.futuregateway.apiserver.v1.TaskService.java
/** * Removes the task. Task is deleted and all the associated activities and * or files removed.// w w w. j a v a2s . c om * * @param id Id of the task to remove */ @DELETE public final void deleteTask(@PathParam("id") final String id) { Task task; EntityManager em = getEntityManager(); try { task = em.find(Task.class, id); if (task == null) { throw new NotFoundException(); } EntityTransaction et = em.getTransaction(); try { et.begin(); em.remove(task); et.commit(); } catch (RuntimeException re) { if (et != null && et.isActive()) { et.rollback(); } log.error(re); log.error("Impossible to remove the task"); em.close(); throw new InternalServerErrorException("Errore to remove " + "the task " + id); } try { Storage store = getStorage(); store.removeAllFiles(Storage.RESOURCE.TASKS, id); } catch (IOException ex) { log.error("Impossible to remove the directory associated with " + "the task " + id); } } catch (IllegalArgumentException re) { log.error("Impossible to retrieve the task list"); log.error(re); throw new BadRequestException("Task '" + id + "' has a problem!"); } finally { em.close(); } }
From source file:com.openmeap.model.ModelServiceImpl.java
@Override public <E extends ModelEntity, T extends ModelEntity> List<T> getOrdered(E entity, String listMethod, Comparator<T> comparator) { EntityManager entityManager = getEntityManager(); entityManager.getTransaction().begin(); entityManager.merge(entity);/*www . j ava 2 s . co m*/ List<T> ents; try { ents = (List<T>) entity.getClass().getMethod(listMethod).invoke(entity); } catch (Exception e) { throw new PersistenceException(e); } Collections.sort(ents, comparator); entityManager.getTransaction().commit(); return ents; }
From source file:com.enioka.jqm.tools.JobManagerHandler.java
/** * Create a {@link com.enioka.jqm.jpamodel.Message} with the given message. The {@link com.enioka.jqm.jpamodel.History} to link to is * deduced from the context./*w w w . ja va 2s . c o m*/ * * @param msg * @throws JqmKillException */ private void sendMsg(String msg) { EntityManager em = Helpers.getNewEm(); try { em.getTransaction().begin(); Helpers.createMessage(msg, ji, em); em.getTransaction().commit(); } finally { em.close(); } }