public void update() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<Post> q = cb.createCriteriaUpdate(Post.class); Root<Post> root = q.from(Post.class); q.set(root.get("approved"), true) .where(root.get("id").in(getCheckedList())); int result = em.createQuery(q).executeUpdate(); log.info("update @" + result); load(); }
public void updateTask(final ToDoList pToDoList) { final CriteriaBuilder lCriteriaBuilder = entityManager.getCriteriaBuilder(); //Creation de la requête d'update final CriteriaUpdate<ToDoList> lCriteriaUpdate = lCriteriaBuilder.createCriteriaUpdate(ToDoList.class); final Root<ToDoList> lRoot = lCriteriaUpdate.from(ToDoList.class); final Path<ToDoList> lPath = lRoot.get("id"); //On utilise la variable pToDoList transmise en parametre de la methode final Expression<Boolean> lExpression = lCriteriaBuilder.equal(lPath, pToDoList.getId()); lCriteriaUpdate.where(lExpression); lCriteriaUpdate.set("libelle", pToDoList.getLibelle()); final Query lQuery = entityManager.createQuery(lCriteriaUpdate); final int lRowCount = lQuery.executeUpdate(); //Si la requête modifie un nombre d'occurrences différent de 1 > erreur //Sinon update fait. if (lRowCount != 1) { final org.hibernate.Query lHQuery = lQuery.unwrap(org.hibernate.Query.class); final String lSql = lHQuery.getQueryString(); throw new RuntimeException("Nombre d'occurences (" + lRowCount + ") modifiés différent de 1 pour " + lSql); } }
@Override public int update(T entity) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaUpdate<T> criteriaUpdate = builder.createCriteriaUpdate(entityClass); Root<T> root = criteriaUpdate.from(entityClass); Field[] fields = entityClass.getDeclaredFields(); Object primaryV = null; String primaryKey = this.getPrimaryKey(); for (Field field : fields) { ReflectionUtils.makeAccessible(field); Object fieldV = ReflectionUtils.getField(field, entity); if (fieldV == null) continue; if (primaryKey.equals(field.getName())) {// 主键不参与修改 primaryV = fieldV; } else { criteriaUpdate.set(root.get(field.getName()), fieldV); } } criteriaUpdate.where(builder.equal(root.get(primaryKey), primaryV)); Query query = entityManager.createQuery(criteriaUpdate); return query.executeUpdate(); }
@Test public void updateBookPrices() { log.info("... updateBookPrices ..."); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); logBookPrices(em); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<Book> update = cb.createCriteriaUpdate(Book.class); Root<Book> root = update.from(Book.class); update.set(Book_.price, cb.prod(root.get(Book_.price), 1.1)); Query query = em.createQuery(update); query.executeUpdate(); logBookPrices(em); em.getTransaction().commit(); em.close(); }
private void softDelete(T entity, LocalDateTime localDateTime) { Assert.notNull(entity, "The entity must not be null!"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<T> update = cb.createCriteriaUpdate((Class<T>) domainClass); Root<T> root = update.from((Class<T>) domainClass); update.set(DELETED_FIELD, localDateTime); final List<Predicate> predicates = new ArrayList<Predicate>(); if (entityInformation.hasCompositeId()) { for (String s : entityInformation.getIdAttributeNames()) predicates.add(cb.equal(root.<ID>get(s), entityInformation.getCompositeIdAttributeValue(entityInformation.getId(entity), s))); update.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); } else update.where(cb.equal(root.<ID>get(entityInformation.getIdAttribute().getName()), entityInformation.getId(entity))); em.createQuery(update).executeUpdate(); }
/** * JAVADOC Method Level Comments * * @param eventName JAVADOC. * @param nodeId JAVADOC. * * @return JAVADOC. */ @Override @Transactional public boolean complete(String eventName, String nodeId) { if (LOG.isDebugEnabled()) { LOG.debug("Cleaning for event '" + eventName + "' and node '" + nodeId + "'"); } CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaUpdate<ClusterControl> cq = cb.createCriteriaUpdate(ClusterControl.class); Root<ClusterControl> root = cq.from(ClusterControl.class); Predicate ep = cb.equal(root.get("event"), eventName); Path<Object> pc = root.get("complete"); Predicate cp = cb.equal(pc, false); Predicate np = cb.equal(root.get("activeNodeId"), nodeId); cq.set(pc, true); int rows = entityManager.createQuery(cq.where(cb.and(ep, cp, np))).executeUpdate(); return rows > 0; }
private void performMove(Sign nodeSign, Long nodeDelta, List nodeIds, Long levelModificator, Class<N> nodeClass) { if (!nodeIds.isEmpty()) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update.set(root.<Long>get(level(nodeClass)), cb.sum(root.<Long>get(level(nodeClass)), levelModificator)); if (Sign.MINUS.equals(nodeSign)) { update.set(root.<Long>get(right(nodeClass)), cb.diff(root.<Long>get(right(nodeClass)), nodeDelta)); update.set(root.<Long>get(left(nodeClass)), cb.diff(root.<Long>get(left(nodeClass)), nodeDelta)); } else if (Sign.PLUS.equals(nodeSign)) { update.set(root.<Long>get(right(nodeClass)), cb.sum(root.<Long>get(right(nodeClass)), nodeDelta)); update.set(root.<Long>get(left(nodeClass)), cb.sum(root.<Long>get(left(nodeClass)), nodeDelta)); } update.where(getPredicates(cb, root, root.get(id(nodeClass)).in(nodeIds))); em.createQuery(update).executeUpdate(); } }
private void updateFields(Sign sign, Long delta, Long start, Long stop, Class<N> nodeClass, String field) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); if (Sign.MINUS.equals(sign)) { update.set(root.<Long>get(field), cb.diff(root.<Long>get(field), delta)); } else if (Sign.PLUS.equals(sign)) { update.set(root.<Long>get(field), cb.sum(root.<Long>get(field), delta)); } update.where(getPredicates(cb, root, cb.greaterThan(root.<Long>get(field), start), cb.lessThan(root.<Long>get(field), stop) )); em.createQuery(update).executeUpdate(); }
/** * WARNING, order will not be honoured by this method * * @param attribute * @param value * * @return */ public <F> int update(SingularAttribute<E, F> attribute, F value) { Preconditions.checkArgument(orders.size() == 0, "Order is not supported for delete"); CriteriaUpdate<E> updateCriteria = builder.createCriteriaUpdate(entityClass); root = updateCriteria.getRoot(); if (predicate != null) { updateCriteria.where(predicate); updateCriteria.set(attribute, value); } Query query = getEntityManager().createQuery(updateCriteria); if (limit != null) { query.setMaxResults(limit); } if (startPosition != null) { query.setFirstResult(startPosition); } int result = query.executeUpdate(); getEntityManager().getEntityManagerFactory().getCache().evict(entityClass); return result; }
@Test public void shouldExecuteCriteriaUpdate() throws Exception { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaUpdate<Employee> c = builder.createCriteriaUpdate(Employee.class); Root<Employee> p = c.from(Employee.class); Predicate condition = builder.ge( p.get(Employee_.salary), new BigDecimal("50000")); c.where(condition); TaxCode directorTaxCode = new TaxCode(504, "Director"); c.set(p.get(Employee_.taxCode), directorTaxCode); utx.begin(); Query query = em.createQuery(c); int rowsAffected = query.executeUpdate(); assertTrue( rowsAffected > 0 ); utx.commit(); }
@Override public int batchUpdateStatus(String zone, AgentStatus status, Set<String> agents, boolean isNot) { return execute(session -> { CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaUpdate<Agent> criteria = builder.createCriteriaUpdate(Agent.class); Root<Agent> from = criteria.from(Agent.class); criteria.set(from.get("status"), status); Predicate whereClause = builder.equal(from.get("path").get("zone"), zone); if (agents == null || agents.size() == 0) { return session.createQuery(criteria).executeUpdate(); } // set agents to where clause Predicate inAgents; if (isNot) { inAgents = builder.not(from.get("path").get("name").in(agents)); } else { inAgents = from.get("path").get("name").in(agents); } criteria.where(builder.and(whereClause, inAgents)); return session.createQuery(criteria).executeUpdate(); }); }
@Override public int updateNotNullOrEmpty(final CmdResult obj) { final Map<Field, Object> notNullFields = ObjectUtil.findNotNullFieldValue(getEntityClass(), obj, Sets.newHashSet(Process.class), Sets.newHashSet("cmdId"), true); // all fields are null if (notNullFields.isEmpty()) { return 0; } return execute(session -> { CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaUpdate<CmdResult> update = builder.createCriteriaUpdate(CmdResult.class); Root<CmdResult> from = update.from(CmdResult.class); for (Map.Entry<Field, Object> entry : notNullFields.entrySet()) { Field field = entry.getKey(); Object value = entry.getValue(); // for cmd result exception type, adaptor will get item of list.. maybe its bug of hibenrate if (value instanceof List) { value = BaseAdaptor.GSON.toJson(value); } update.set(field.getName(), value); } update.where(builder.equal(from.get(getKeyName()), obj.getCmdId())); return session.createQuery(update).executeUpdate(); }); }
/** * {@inheritDoc} */ @Override public <T extends BaseEntity> int updateByCriteria(UpdateCriteria<T> criteria) { EntityManager em = null; EntityTransaction txn = null; try { em = this.emf.createEntityManager(); txn = JpaUtil.getTransaction(em); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<T> cu = cb.createCriteriaUpdate(criteria.getEntity()); criteria.getUpdateAttributes().forEach(cu::set); Root<T> root = cu.from(criteria.getEntity()); int rowsUpdated = em .createQuery(cu.where(cb.and(JpaUtil.getPredicates(criteria.getCriteriaAttributes(), cb, root)))) .executeUpdate(); txn.commit(); LOGGER.debug("No. of rows updated: {}", rowsUpdated); return rowsUpdated; } catch (RuntimeException ex) { JpaUtil.setRollbackOnly(txn); LOGGER.error(ex.getMessage(), ex); throw new PersistenceException(ex.getMessage(), ex); } finally { JpaUtil.rollbackTransaction(txn); JpaUtil.closeEntityManager(em); } }
public Query createQuery(CriteriaUpdate criteria) { DefaultAccessManager.Instance.register(accessManager); FilterResult<CriteriaUpdate> filterResult = entityFilter.filterQuery(criteria); if (filterResult.getQuery() == null) { return new EmptyResultQuery(super.createQuery(criteria)); } else { return createQuery(super.createQuery(filterResult.getQuery()), filterResult); } }
private From<?, ?> getFrom(CommonAbstractCriteria query, Alias alias) { if (query instanceof CriteriaUpdate) { return ((CriteriaUpdate<?>)query).getRoot(); } else if (query instanceof CriteriaDelete) { return ((CriteriaUpdate<?>)query).getRoot(); } else { return getFrom((AbstractQuery<?>)query, alias); } }
@Test public void shouldBulkUpdateCriteria() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<Address> update = cb.createCriteriaUpdate(Address.class); //<3> Root<Address> i = update.from(Address.class); update.set(i.get("disable"), true); update.where(cb.greaterThan(i.get("id"), 0l)); int updatedEntities = em.createQuery(update).executeUpdate(); //<4> Assertions.assertThat(updatedEntities).isEqualTo(30); Assertions.assertThat(addressRepo.findByDisableTrue()).hasSize(30); }
public static <E> SqmUpdateStatement interpretUpdateCriteria(CriteriaUpdate<E> criteria, ParsingContext parsingContext) { if ( !JpaCriteriaUpdate.class.isInstance( criteria ) ) { throw new IllegalArgumentException( "CriteriaUpdate to interpret must implement org.hibernate.sqm.query.JpaCriteriaUpdate" ); } final CriteriaInterpreter interpreter = new CriteriaInterpreter( parsingContext ); return interpreter.visitUpdateCriteria( (JpaCriteriaUpdate<E>) criteria ); }
@Nonnegative @Override @SuppressWarnings({ CompilerWarnings.UNCHECKED }) public long update(EntityManager entityManager) { CriteriaUpdate<T> criteriaQuery = ((CriteriaUpdate<T>) this.criteriaBuilder.createCriteriaUpdate(this.entityImplClass)); return this.update(entityManager, criteriaQuery, criteriaQuery.from(((Class<T>) this.entityImplClass))); }
@Nonnegative @Override @SuppressWarnings({ CompilerWarnings.UNCHECKED }) public <U> long update(EntityManager entityManager, CriteriaUpdate<U> criteriaQuery, Root<T> root) { Query query = this.buildQuery(entityManager, criteriaQuery, root, this.maxResults); if (query == null) { return 0L; } return query.executeUpdate(); }
private void updateParentField(Optional<N> newParent, NestedNodeInfo<N> node, Class<N> nodeClass) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update.set(root.get(parent(nodeClass)), newParent.isPresent() ? newParent.get() : null) .where(getPredicates(cb, root, cb.equal(root.get(id(nodeClass)), node.getId()))); em.createQuery(update).executeUpdate(); }
private void updateDeletedNodeChildren(NestedNodeInfo<N> node, Class<N> nodeClass) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update.set(root.<Long>get(right(nodeClass)), cb.diff(root.<Long>get(right(nodeClass)), 1L)) .set(root.<Long>get(left(nodeClass)), cb.diff(root.<Long>get(left(nodeClass)), 1L)) .set(root.<Long>get(level(nodeClass)), cb.diff(root.<Long>get(level(nodeClass)), 1L)); update.where(getPredicates(cb, root, cb.lessThan(root.<Long>get(right(nodeClass)), node.getRight()), cb.greaterThan(root.<Long>get(left(nodeClass)), node.getLeft())) ); em.createQuery(update).executeUpdate(); }
private void updateFieldsBeforeSingleNodeRemoval(Long from, Class<N> nodeClass, String field) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update.set(root.<Long>get(field), cb.diff(root.<Long>get(field), 2L)) .where(getPredicates(cb, root, cb.greaterThan(root.<Long>get(field), from))); em.createQuery(update).executeUpdate(); }
private void updateNodesParent(NestedNodeInfo<N> node, Optional<N> parent, Class<N> nodeClass) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); N newParent = parent.isPresent() ? parent.get() : null; update.set(root.get(parent(nodeClass)), newParent) .where(getPredicates(cb, root, cb.greaterThanOrEqualTo(root.<Long>get(left(nodeClass)), node.getLeft()), cb.lessThanOrEqualTo(root.<Long>get(right(nodeClass)), node.getRight()), cb.equal(root.<Long>get(level(nodeClass)), node.getLevel() + 1) )); em.createQuery(update).executeUpdate(); }
private void updateFieldsAfterSubtreeRemoval(Long from, Long delta, Class<N> nodeClass, String field) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update.set(root.<Long>get(field), cb.diff(root.<Long>get(field), delta)) .where(getPredicates(cb, root, cb.greaterThan(root.<Long>get(field), from))); em.createQuery(update).executeUpdate(); }
private void updateFields(Long from, Mode mode, Class<N> nodeClass, String fieldName) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update.set(root.<Long>get(fieldName), cb.sum(root.<Long>get(fieldName), 2L)); if (applyGte(mode)) { update.where(getPredicates(cb, root, cb.greaterThanOrEqualTo(root.<Long>get(fieldName), from))); } else { update.where(getPredicates(cb, root, cb.greaterThan(root.<Long>get(fieldName), from))); } em.createQuery(update).executeUpdate(); }
@Override public void destroyTree(Class<N> nodeClass) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update .set(root.<Long>get(left(nodeClass)), 0L) .set(root.<Long>get(right(nodeClass)), 0L) .set(root.<Long>get(level(nodeClass)), 0L) .where(getPredicates(cb, root)); em.createQuery(update).executeUpdate(); }
private void resetFirst(N first, Class<N> nodeClass) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<N> update = cb.createCriteriaUpdate(nodeClass); Root<N> root = update.from(nodeClass); update.set(root.<Long>get(left(nodeClass)), 1L).set(root.<Long>get(right(nodeClass)), 2L) .where(getPredicates(cb, root, cb.equal(update.getRoot().get(id(nodeClass)), first.getId()))); em.createQuery(update).executeUpdate(); }
public void updateMovie() { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaUpdate<Movie> updateCriteria = builder.createCriteriaUpdate(Movie.class); Root<Movie> updateRoot = updateCriteria.from(Movie.class); updateCriteria.where(builder.equal(updateRoot.get(Movie_.name), "Inception")); updateCriteria.set(updateRoot.get(Movie_.name), "INCEPTION"); Query q = em.createQuery(updateCriteria); q.executeUpdate(); em.flush(); }
@Override public Query createQuery(final CriteriaUpdate updateQuery) { final Timer timer = Op.createQuery.start(this.timer, this); try { return getEntityManager().createQuery(updateQuery); } finally { timer.stop(); } }
@Override public Query createQuery(@SuppressWarnings("rawtypes") CriteriaUpdate updateQuery) { logger.error("Thread: {} using entity Manager {}", Thread.currentThread().getId(), emid); return em.createQuery(updateQuery); }
@Override public <T> CriteriaUpdate<T> createCriteriaUpdate(Class<T> targetEntity) { // TODO Auto-generated method stub return null; }
@Override public Query createQuery(CriteriaUpdate arg0) { return this.original.createQuery(arg0); }
@Override public Query createQuery(CriteriaUpdate updateQuery) { // TODO Auto-generated method stub return null; }
@Override public Query createQuery(CriteriaUpdate arg0) { return nativeEntityManager.createQuery(arg0); }
@Override public Query createQuery(CriteriaUpdate updateQuery) { return null; }
public FilterResult<CriteriaUpdate> filterQuery(CriteriaUpdate query) { return filterQuery(query, query.getRoot()); }