@Override public T add(T entry) { em.getTransaction().begin(); T newEntry = em.merge(entry); em.getTransaction().commit(); return newEntry; }
/** This convenience method is set aside for readability. */ private void getHibernateSession() { // import org.jboss.jpa.tx.TransactionScopedEntityManager; // Find a method for getting a hibernate session. Method[] emMethods = em.getClass().getMethods(); for (Method method : emMethods) { if (method.getName().equals("getHibernateSession")) { // Once found, invoke the method. try { Object returnObj = method.invoke(em); if (returnObj instanceof Session) { session = (Session) returnObj; } else { logger.warn( "Invoking 'getHibernateSession()' returned type of " + returnObj.getClass().getName() + " instead of a hibernate session."); } } catch (Exception ex) { logger.error( "Failed to invoke the getter to obtain the hibernate session " + ex.getMessage()); ex.printStackTrace(); } } } if (session == null) { logger.error("Failed to find hibernate session from " + em.toString()); } }
private List<Vote> findVoteEntitiesByPollAltIds( Long pollId, Long altId, boolean all, int maxResults, int firstResult) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Vote> q = cb.createQuery(Vote.class); Root<Vote> vote = q.from(Vote.class); ParameterExpression<Long> pid = cb.parameter(Long.class); ParameterExpression<Long> aid = cb.parameter(Long.class); q.select(vote) .where( cb.and( cb.equal(vote.get(Vote_.alternative).get(Alternative_.poll).get(Poll_.id), pid), cb.equal(vote.get(Vote_.alternative).get(Alternative_.id), aid))); TypedQuery<Vote> query = em.createQuery(q); query.setParameter(pid, pollId).setParameter(aid, altId); if (!all) { query.setMaxResults(maxResults); query.setFirstResult(firstResult); } List<Vote> results = query.getResultList(); System.out.println(">>>>>>>>>>>>>>>>>>>> Votes: " + results); return results; }
/** * Attribute für einen Lehrer verändern * * @param lid ID des Lehrers * @param l Lehrerobjekt * @return Lehrerobjekt oder null bei Fehlern */ @POST @Produces({"application/json; charset=iso-8859-1"}) @Path("admin/id/{idlehrer}") public Lehrer setLehrer(@PathParam("idlehrer") String lid, Lehrer l) { em.getEntityManagerFactory().getCache().evictAll(); Lehrer le = em.find(Lehrer.class, lid); if (le != null) { if (l.getEMAIL() != null) { le.setEMAIL(l.getEMAIL()); } if (l.getIdplain() != null) { le.setIdplain(l.getIdplain()); } if (l.getNNAME() != null) { le.setNNAME(l.getNNAME()); } if (l.getTELEFON() != null) { le.setTELEFON(l.getTELEFON()); } if (l.getVNAME() != null) { le.setVNAME(l.getVNAME()); } em.merge(le); } return le; }
@Override public List<BluetoothDwell> getBluetoothDwellInRangeByCampaign( Date start, Date end, Company c, Campaign camp) { Query q; if (start == null || end == null) { q = em.createQuery( "SELECT bdwell FROM BluetoothDwell bdwell WHERE bdwell.company = ?1 and bdwell.campaign = ?2"); q.setParameter(1, c); q.setParameter(2, camp); } else { q = em.createQuery( "SELECT bdwell FROM BluetoothDwell bdwell WHERE bdwell.company = ?1 AND bdwell.eventDate BETWEEN ?2 AND ?3 AND bdwell.campaign = ?4"); q.setParameter(1, c); q.setParameter(2, start, TemporalType.TIMESTAMP); q.setParameter(3, end, TemporalType.TIMESTAMP); q.setParameter(4, camp); } List<BluetoothDwell> results = (List<BluetoothDwell>) q.getResultList(); if (results.size() > 0) { return results; } return null; }
/** @return */ private ArrayList<ReferenceDataRefDataType> getUsedRefSpecialtySchemes() { System.out.println("\n========> Getting Used specialtyscheme references"); ArrayList<ReferenceDataRefDataType> refColl = new ArrayList<ReferenceDataRefDataType>(); Query query = null; int startRec = refDetails.getStartingRecNumber(); int maxDisplay = refDetails.getMaxRecordsToShow(); if ((refDetails.getLookupSystem().getCodeSystem() == null) || (refDetails.getLookupSystem().getCodeSystem().isEmpty())) { query = em.createNamedQuery("KMSpecialty.findAllDistinctScheme"); } else { query = em.createNamedQuery("KMSpecialty.findAllDistinctSchemeByWildcard"); query.setParameter( "terminologyScheme", refDetails.getLookupSystem().getCodeSystem().toUpperCase() + "%"); } query.setFirstResult(startRec); query.setMaxResults(maxDisplay); List<String> foundList = (List<String>) query.getResultList(); for (int r = 0; r < foundList.size(); r++) { ReferenceDataRefDataType aRefData = new ReferenceDataRefDataType(); aRefData.setId( 0); // TODO Need to pull the ID for each one of this type from ref_specialty_type // ..another call aRefData.setName(foundList.get(r)); refColl.add(aRefData); } return refColl; }
/** * Service method to return all StockCategory from database * * @return */ public List<StockCategory> findAllStockCategories() { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<StockCategory> criteria = criteriaBuilder.createQuery(StockCategory.class); Root<StockCategory> stockCategory = criteria.from(StockCategory.class); criteria.select(stockCategory); return entityManager.createQuery(criteria).getResultList(); }
public static void assignUserToProject(Long projectID, Long userID) { EntityManager em = getEM(); ProjectUser pu = em.find(ProjectUser.class, userID); em.getTransaction().begin(); pu.setContributor(em.find(Project.class, projectID)); em.getTransaction().commit(); }
public PurchaseDTO createPurchase(PurchaseDTO purchase) { PurchaseEntity entity = PurchaseConverter.persistenceDTO2Entity(purchase); entityManager.getTransaction().begin(); entityManager.persist(entity); entityManager.getTransaction().commit(); return PurchaseConverter.entity2PersistenceDTO(entity); }
public static Project createProject(Project project) { EntityManager em = getEM(); em.getTransaction().begin(); em.persist(project); em.getTransaction().commit(); return project; }
public static ProjectUser createUser(ProjectUser user) { EntityManager em = getEM(); em.getTransaction().begin(); em.persist(user); em.getTransaction().commit(); return user; }
public boolean setStock(List<DetailDTO> dtl) { for (DetailDTO detailDTO : dtl) { // NEW com.server.entity.beans.TblMaterial(c.idtblMaterial, c.stock ) // Query query = em.createQuery("SELECT c.idtblMaterial, c.stock, // c.idTipomaterial.idTipomaterial, c.subFamiliasidsubFam.idsubFam, c.idArea.idArea, c.costo, // c.noParte, c.descripcion, c.imagen, c.nombre" // + " FROM TblMaterial c WHERE c.idtblMaterial = :id "); // query.setParameter("id", detailDTO.getIdMaterial()); // Object[] res = (Object[]) query.getSingleResult(); TypedQuery<TblMaterial> query = em.createNamedQuery("TblMaterial.findByIdtblMaterial", TblMaterial.class); query.setParameter("idtblMaterial", detailDTO.getIdMaterial()); TblMaterial temp = query.getSingleResult(); // temp.setIdtblMaterial((Integer) res[0]); int oldStock = temp.getStock(); temp.setStock(oldStock + detailDTO.getRegresados()); // temp.setStock((Integer) res[1] + detailDTO.getCantidad()); // temp.setIdTipomaterial(new TblTipomaterial((Integer) res[2])); // temp.setSubFamiliasidsubFam(new Subfamilias((Integer) res[3])); // temp.setIdArea(new TblArea((Integer) res[4])); // temp.setCosto((Long) res[5]); // temp.setNoParte((String) res[6]); // temp.setDescripcion((String) res[7]); // temp.setImagen((String) res[8]); // temp.setNombre((String) res[9]); this.edit(temp); } em.flush(); return false; }
private void btnOKActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnOKActionPerformed EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); TradeForm myTradeForm = em.merge(tradeForm); em.lock(myTradeForm, LockModeType.OPTIMISTIC); myTradeForm.setSubtext(txtZusatz.getText()); DosageForm dosageForm = em.merge((DosageForm) cmbForm.getSelectedItem()); em.lock(dosageForm, LockModeType.OPTIMISTIC); myTradeForm.setDosageForm(dosageForm); em.getTransaction().commit(); tradeForm = myTradeForm; } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } dispose(); } // GEN-LAST:event_btnOKActionPerformed
private void initDialog() { initPhase = true; cmbDaysWeeks.setModel( new DefaultComboBoxModel( new String[] {SYSTools.xx("misc.msg.Days"), SYSTools.xx("misc.msg.weeks")})); cbWeightControlled.setText( SYSTools.xx("opde.medication.medproduct.wizard.subtext.weightControlled")); cbWeightControlled.setSelected(tradeForm.isWeightControlled()); cbExpiresAfterOpened.setText(SYSTools.xx("tradeform.subtext.expiresAfterOpenedIn")); cbExpiresAfterOpened.setSelected(tradeForm.getDaysToExpireAfterOpened() != null); txtExpiresIn.setEnabled(cbExpiresAfterOpened.isSelected()); cmbDaysWeeks.setEnabled(cbExpiresAfterOpened.isSelected()); Pair<Integer, Integer> pair = TradeFormTools.getExpiresIn(tradeForm); if (pair != null) { txtExpiresIn.setText( pair.getFirst() > 0 ? pair.getFirst().toString() : pair.getSecond().toString()); cmbDaysWeeks.setSelectedIndex(pair.getFirst() > 0 ? 0 : 1); } EntityManager em = OPDE.createEM(); Query query = em.createQuery("SELECT m FROM DosageForm m ORDER BY m.preparation, m.usageText"); cmbForm.setModel(new DefaultComboBoxModel(query.getResultList().toArray(new DosageForm[] {}))); cmbForm.setRenderer(DosageFormTools.getRenderer(0)); em.close(); cmbForm.setSelectedItem(tradeForm.getDosageForm()); txtZusatz.setText(SYSTools.catchNull(tradeForm.getSubtext())); btnAdd.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "opde.medication")); btnEdit.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "opde.medication")); initPhase = false; }
public List<Transportista> busquedaPersonalizada(BusquedaTransportistaCriteria criteria) { String query = "SELECT t FROM Transportista t WHERE t.empresa = :empresa AND t.eliminado = false"; // Nombre if (criteria.isBuscarPorNombre() == true) { String[] terminos = criteria.getNombre().split(" "); for (int i = 0; i < terminos.length; i++) { query += " AND t.nombre LIKE '%" + terminos[i] + "%'"; } } // Localidad if (criteria.isBuscarPorLocalidad() == true) { query = query + " AND t.localidad = " + criteria.getLocalidad().getId_Localidad(); } // Provincia if (criteria.isBuscarPorProvincia() == true) { query = query + " AND t.localidad.provincia = " + criteria.getProvincia().getId_Provincia(); } // Pais if (criteria.isBuscarPorPais() == true) { query = query + " AND t.localidad.provincia.pais = " + criteria.getPais().getId_Pais(); } query = query + " ORDER BY t.nombre ASC"; EntityManager em = PersistenceUtil.getEntityManager(); TypedQuery<Transportista> typedQuery = em.createQuery(query, Transportista.class); typedQuery.setParameter("empresa", criteria.getEmpresa()); List<Transportista> transportistas = typedQuery.getResultList(); em.close(); return transportistas; }
public PurchaseDTO getPurchase(Long id) { entityManager.getTransaction().begin(); PurchaseDTO result = PurchaseConverter.entity2PersistenceDTO(entityManager.find(PurchaseEntity.class, id)); entityManager.getTransaction().commit(); return result; }
/** * Deletes the authorization after removing it from any groups that might be referring to it * * @param em the entity manager reference * @param id the ID for authorizatino entity * @throws PersistenceException if there were any errors deleting the authorization */ static void deleteAuthorization(EntityManager em, long id) throws PersistenceException { Authorization auth = em.find(Authorization.class, id); // may return null, if this entity is not saved, in which // case don't do anything. if (auth == null) { return; } // Iterate through all groups and remove the authorization from them Set<SummaryGroup> groups = auth.getGroups(); if (groups != null) { for (SummaryGroup g : groups) { Group group = new SingleGroupQuery(g.getId()).fetch(); Set<Authorization> auths = group.getAuthorizations(); HashSet<Authorization> updated = new HashSet<Authorization>(); for (Authorization a : auths) { if (a.getId() != auth.getId()) { updated.add(a); } } group.setAuthorizations(updated); group.save(); } } em.remove(em.getReference(Authorization.class, auth.getId())); }
public int update(int oid, String quantity, String memo) { // 更新揀貨單的揀貨數量 logger.debug( "OrderPlaceDDAO.update: " + "pickId: " + oid + ", quantity: " + quantity + ", memo: " + memo); EntityManager em = XPersistence.getManager(); OrderPlaceD bean = em.find(OrderPlaceD.class, oid); logger.debug("OrderPlaceD.update: orderPlaceD: " + bean); if (bean != null) { // bean.setQuantity(quantity); bean.setRemark(memo); try { em.merge(bean); XPersistence.commit(); } catch (Exception e) { logger.error("OrderPlaceD.update: " + e); } return 1; // 1:成功 } return 0; // 0:失敗 }
@Override public List<Category> getCategoryByParameters(Map<String, Object> parameters) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Category> cq = cb.createQuery(Category.class); Root<Category> r = cq.from(Category.class); Join<RssUser, Category> ru = r.join("rssUserList", JoinType.LEFT); Join<RssUser, Rss> rss = ru.join("rss", JoinType.LEFT); Predicate p = cb.conjunction(); for (Map.Entry<String, Object> param : parameters.entrySet()) { if (param.getKey().equals("rssId")) { p = cb.and(p, cb.equal(rss.get("rssId"), param.getValue())); } else if (param.getKey().equals("guid")) { p = cb.and(p, cb.equal(r.get(param.getKey()), param.getValue())); } } p = cb.or(p, cb.equal(r.get("categoryId"), DEFAULT_CATEGORY_ID)); cq.distinct(true); cq.multiselect().where(p); TypedQuery typedQuery = em.createQuery(cq); List<Category> resultList = typedQuery.getResultList(); return resultList; }
@Override public List<Korisnik> sviKorisnici() { em.getEntityManagerFactory().getCache().evictAll(); Query q = em.createNamedQuery("Korisnik.findAll"); List<Korisnik> korisnici = q.getResultList(); return korisnici; }
/** * Returns a collection of bounds for reactions included in the given's model metabolism. Note * that it has to be a sum of bounds of the parent model (if the given model has a parent) and the * bounds directly associated with current model. * * @param model * @return collection of bounds for the given model */ Collection<EBounds> getBoundsForModel(EModel model, EntityManager em) { if (model.getParent() == null) { return model.getEBoundsCollection(); } else { /* * There are two sources of bounds for each model. * First, we retrieve bounds that have been defined for this model */ List<EBounds> res1 = em.createQuery("SELECT e FROM EBounds e WHERE e.model = :model") .setParameter("model", model) .getResultList(); /* * The remaining bounds are taken from the parent model */ List<EBounds> res2 = em.createQuery( " SELECT b FROM EModel m, EBounds b WHERE " + " m.id = :modelID AND m.parent IS NOT NULL AND " + " b.model = m.parent AND NOT EXISTS (SELECT c " + " FROM EBounds c WHERE c.model = :model AND " + " b.reaction = c.reaction )") .setParameter("modelID", model.getId()) .setParameter("model", model) .getResultList(); res1.addAll(res2); return res1; } }
/** * A strategy method to lock an object with an exclusive lock so that it can be processed * * @param entity the entity to be locked * @param entityManager entity manager * @return true if the entity was locked */ protected boolean lockEntity(Object entity, EntityManager entityManager) { if (!getEndpoint().isConsumeLockEntity()) { return true; } try { LOG.debug("Acquiring exclusive lock on entity: {}", entity); if (isSkipLockedEntity()) { entityManager.lock(entity, lockModeType, NOWAIT); } else { entityManager.lock(entity, lockModeType); } return true; } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to achieve lock on entity: " + entity + ". Reason: " + e, e); } if (e instanceof PessimisticLockException || e instanceof OptimisticLockException) { // transaction marked as rollback can't continue gracefully throw (PersistenceException) e; } // TODO: Find if possible an alternative way to handle results of native queries. // Result of native queries are Arrays and cannot be locked by all JPA Providers. if (entity.getClass().isArray()) { return true; } return false; } }
/** * Finds a Person in the database given its id. * * @param personId The id of the person * @return The found person */ public static Person getPersonById(int personId) { EntityManager em = Assignment3Dao.instance.createEntityManager(); Person person = em.find(Person.class, personId); if (person != null) em.refresh(person); Assignment3Dao.instance.closeConnections(em); return person; }
@Override public void saveConference( String title, Date start, Date end, String room, String website, List<Stakeholder> stakeholders) { if (stakeholders == null) stakeholders = new ArrayList<>(); Conference c = new Conference(); List<Key> keys = new ArrayList<>(); try { for (Stakeholder s : stakeholders) { keys.add(s.getId()); } c = new Conference(title, start, end, room, website, keys); em.persist(c); } finally { em.close(); } try { em = EMF.get().createEntityManager(); for (Key k : keys) { Stakeholder s = em.find(Stakeholder.class, k); s.addConference(c.getId()); } } finally { em.close(); } }
/** * Adding New SurveyKind * * @param record * @return * @throws Exception */ public SurveyKind addSurveyKind(SurveyKind SurveyKind) throws Exception { EntityManager oracleManager = null; Object transaction = null; try { String log = "Method:CommonDMI.addSurveyKind."; oracleManager = EMF.getEntityManager(); transaction = EMF.getTransaction(oracleManager); // sysdate Timestamp recDate = new Timestamp(System.currentTimeMillis()); String loggedUserName = SurveyKind.getLoggedUserName(); RCNGenerator.getInstance().initRcn(oracleManager, recDate, loggedUserName, log); oracleManager.persist(SurveyKind); oracleManager.flush(); SurveyKind = oracleManager.find(SurveyKind.class, SurveyKind.getSurvey_kind_id()); SurveyKind.setLoggedUserName(loggedUserName); EMF.commitTransaction(transaction); log += ". Inserting Finished SuccessFully. "; logger.info(log); return SurveyKind; } catch (Exception e) { EMF.rollbackTransaction(transaction); if (e instanceof CallCenterException) { throw (CallCenterException) e; } logger.error("Error While Insert SurveyKind Into Database : ", e); throw new CallCenterException("შეცდომა მონაცემების შენახვისას : " + e.toString()); } finally { if (oracleManager != null) { EMF.returnEntityManager(oracleManager); } } }
@Override public void saveStakeholder( String name, String type, String email, String website, List<Conference> conferences) { if (conferences == null) conferences = new ArrayList<>(); Stakeholder s = new Stakeholder(); List<Key> keys = new ArrayList<>(); try { for (Conference c : conferences) { keys.add(c.getId()); } s = new Stakeholder(name, type, email, website, keys); em.persist(s); } finally { em.close(); } try { em = EMF.get().createEntityManager(); for (Key k : keys) { Conference c = em.find(Conference.class, k); c.addStakeholder(s.getId()); } } finally { em.close(); } }
@Override public boolean deleteUser(Long userId) { User user = entityManager.find(User.class, userId); entityManager.remove(user); return true; }
/** Ensures that transactions are rolled back when a runtime exception occurs. */ public void testTransactionRolledBackOnRuntimeException() { /* * Create mock entity manager factory which returns a mock * entity manager when asked. */ EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = mock(EntityManager.class); when(emf.create()).thenReturn(em); EntityTransaction tx = mock(EntityTransaction.class); when(em.getTransaction()).thenReturn(tx); Injector injector = Guice.createInjector(new TestModule(emf, true)); OuterTransactedClass outer = injector.getInstance(OuterTransactedClass.class); try { outer.doSomethingInATransaction(); fail("A runtime exception should have been thrown"); } catch (RuntimeException ignored) { } // emf.create should only have been called once. verify(emf).create(); verify(tx).begin(); verify(tx).rollback(); verify(em).close(); }
public int getVoteCount() { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Vote> rt = cq.from(Vote.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); }
@Override public List<T> getList() { CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(getEntityClass()); Root<T> root = query.from(getEntityClass()); query.select(root); return em.createQuery(query).getResultList(); }