public <E> Predicate byEntitySelectors( Root<E> root, CriteriaBuilder builder, SearchParameters sp) { List<EntitySelector<?, ?, ?>> selectors = sp.getEntities(); List<Predicate> predicates = newArrayList(); for (EntitySelector<?, ?, ?> s : selectors) { @SuppressWarnings("unchecked") EntitySelector<? super E, ? extends Identifiable<?>, ?> selector = (EntitySelector<? super E, ? extends Identifiable<?>, ?>) s; if (selector.isNotEmpty()) { List<Predicate> selectorPredicates = newArrayList(); for (Identifiable<?> selection : selector.getSelected()) { selectorPredicates.add(builder.equal(getExpression(root, selector), selection.getId())); } if (TRUE == selector.getIncludeNull()) { selectorPredicates.add(builder.or(builder.isNull(getExpression(root, selector)))); } predicates.add(JpaUtil.orPredicate(builder, selectorPredicates)); } else if (selector.isIncludeNullSet()) { if (selector.getIncludeNull()) { predicates.add(builder.isNull(getExpression(root, selector))); } else { predicates.add(builder.isNotNull(getExpression(root, selector))); } } } return JpaUtil.concatPredicate(sp, builder, predicates); }
public static void main(String[] args) throws IOException { EntityManager manager = JpaUtil.getEntityManager(); Veiculo veiculo = manager.find(Veiculo.class, 1L); if (veiculo.getFoto() != null) { BufferedImage image = ImageIO.read(new ByteArrayInputStream(veiculo.getFoto())); JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image))); } else { System.out.println("Veículo não posui foto."); } manager.close(); JpaUtil.close(); }
public static <E> Predicate byRanges( Root<E> root, CriteriaQuery<?> query, CriteriaBuilder builder, final List<Range<?, ?>> ranges, final Class<E> type) { List<Predicate> predicates = newArrayList(); for (Range<?, ?> r : ranges) { @SuppressWarnings("unchecked") Range<E, ?> range = (Range<E, ?>) r; if (range.isSet()) { Predicate rangePredicate = buildRangePredicate(range, root, builder); if (rangePredicate != null) { if (!range.isIncludeNullSet() || range.getIncludeNull() == FALSE) { predicates.add(rangePredicate); } else { predicates.add(builder.or(rangePredicate, builder.isNull(root.get(range.getField())))); } } // no range at all, let's take the opportunity to keep only null... if (TRUE == range.getIncludeNull()) { predicates.add(builder.isNull(root.get(range.getField()))); } else if (FALSE == range.getIncludeNull()) { predicates.add(builder.isNotNull(root.get(range.getField()))); } } } return JpaUtil.andPredicate(builder, predicates); }
private Map<String, Object> getPropertyConstraints( Object entity, Class<?> entityClass, UniqueConstraint u, String prefix) { Map<String, Object> values = newHashMap(); for (String column : u.columnNames()) { Method method = columnNameToMethod(entityClass, column); if (method != null) { values.put(prefix + jpaUtil.methodToProperty(method), invokeMethod(method, entity)); } else { Field field = columnNameToField(entityClass, column); if (field != null) { values.put(prefix + field.getName(), jpaUtil.getValueFromField(field, entity)); } } } return values; }
private String compositeUniqueConstraintErrorCode( Identifiable<?> entity, UniqueConstraint uniqueConstraint) { return WordUtils.uncapitalize(jpaUtil.getEntityName(entity)) + "_" + (uniqueConstraint.name() == null ? "composite_unique_constraint_error" : uniqueConstraint.name().toLowerCase()); }
@Override public MeasuringMethod mostRecent() { EntityManager em = JpaUtil.getCurrentEntityManager(); TypedQuery<MeasuringMethod> query = em.createNamedQuery("MeasuringMethod.mostRecent", MeasuringMethod.class); try { return query.setMaxResults(1).getSingleResult(); } catch (NoResultException ex) { return null; } }
@Override public MeasuringMethod findByCode(String code) { EntityManager em = JpaUtil.getCurrentEntityManager(); TypedQuery<MeasuringMethod> query = em.createNamedQuery("MeasuringMethod.findByCode", MeasuringMethod.class); try { return query.setParameter("code", code).getSingleResult(); } catch (NoResultException ex) { return null; } }
/** @see io.apiman.manager.api.core.IStorage#rollbackTx() */ protected void rollbackTx() { if (activeEM.get() == null) { throw new RuntimeException("Transaction not active."); // $NON-NLS-1$ } try { JpaUtil.rollbackQuietly(activeEM.get()); } finally { activeEM.get().close(); activeEM.set(null); } }
@Override public void createOrUpdate(MeasuringMethod method) { EntityManager em = JpaUtil.getCurrentEntityManager(); MeasuringMethod method2 = findByCode(method.getCode()); if (method2 == null) { logger.debug("Creating " + method); em.persist(method); } else { logger.debug("Updating " + method); method2.update(method); } }
/** * Busca una instancia en la tabla de mecenazgos usando el id del mecenazgo. * * @param pidMecenazgo: id del mecenazgo */ public static Mecenazgo buscar(Mecenazgo pMecenazgo) { EntityManager em = JpaUtil.getEntityManagerFactory().createEntityManager(); Mecenazgo mecenazgo = null; try { mecenazgo = em.find(Mecenazgo.class, pMecenazgo); } catch (Exception ex) { System.out.println("Error"); ex.printStackTrace(); } finally { em.close(); } return mecenazgo; }
/** * Actualiza una instancia en la tabla de mecenazgos. * * @param pmecenazgo: Objeto Mecenazgo. */ public static void borrar(Mecenazgo pmecenazgo) { EntityManager em = JpaUtil.getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); try { Mecenazgo pMerge = em.merge(pmecenazgo); em.remove(pMerge); em.getTransaction().commit(); System.out.println("Borrado exitoso"); } catch (Exception ex) { ex.printStackTrace(); } finally { em.close(); } }
/** * Crea una instancia en la tabla de mecenazgos. * * @param pmecenazgo: Objeto Mecenazgo. */ public static void crear(Mecenazgo pmecenazgo) { EntityManager em = JpaUtil.getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); try { em.persist(pmecenazgo); em.getTransaction().commit(); } catch (Exception ex) { em.getTransaction().rollback(); System.out.println("Error al guardar"); ex.printStackTrace(); } finally { em.close(); } }
private List<String> validateSimpleUniqueConstraintsDefinedOnFields(Identifiable<?> entity) { Class<?> entityClass = getClassWithoutInitializingProxy(entity); List<String> errors = newArrayList(); for (Field field : entityClass.getFields()) { Column column = field.getAnnotation(Column.class); if (column != null && column.unique()) { Map<String, Object> values = newHashMap(); values.put(field.getName(), jpaUtil.getValueFromField(field, entity)); if (existsInDatabaseOnAllObjects(entity, values)) { errors.add(simpleUniqueConstraintError(entity, field.getName())); } } } return errors; }
/** * Actualiza una instancia en la tabla de mecenazgos. * * @param pmecenazgo: Objeto Mecenazgo. */ public static void actualizar(Mecenazgo pmecenazgo) { EntityManager em = JpaUtil.getEntityManagerFactory().createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.merge(pmecenazgo); tx.commit(); System.out.println("Actualizacion exitosa"); } catch (Exception ex) { tx.rollback(); System.out.println("Error"); ex.printStackTrace(); } finally { em.close(); } }
private List<String> validateSimpleUniqueConstraintsDefinedOnMethods(Identifiable<?> entity) { Class<?> entityClass = getClassWithoutInitializingProxy(entity); List<String> errors = newArrayList(); for (Method method : entityClass.getMethods()) { Column column = entityClass.getAnnotation(Column.class); if (column != null && column.unique()) { Map<String, Object> values = newHashMap(); String property = jpaUtil.methodToProperty(method); values.put(property, invokeMethod(method, entity)); if (existsInDatabaseOnAllObjects(entity, values)) { errors.add(simpleUniqueConstraintError(entity, property)); } } } return errors; }
public <T> List<T> findByNamedQuery(SearchParameters sp) { if (sp == null || !sp.hasNamedQuery()) { throw new IllegalArgumentException( "searchParameters must be non null and must have a namedQuery"); } Query query = entityManager.createNamedQuery(sp.getNamedQuery()); String queryString = getQueryString(query); // append order by if needed if (queryString != null && sp.hasOrders()) { // create the sql restriction clausis StringBuilder orderClausis = new StringBuilder("order by "); boolean first = true; for (OrderBy orderBy : sp.getOrders()) { if (!first) { orderClausis.append(", "); } orderClausis.append(orderBy.getPath()); orderClausis.append(orderBy.isOrderDesc() ? " desc" : " asc"); first = false; } log.debug("appending: [{}] to {}", orderClausis, queryString); query = recreateQuery(query, queryString + " " + orderClausis.toString()); } // pagination jpaUtil.applyPagination(query, sp); // named parameters setQueryParameters(query, sp); // execute @SuppressWarnings("unchecked") List<T> result = query.getResultList(); if (result != null) { log.debug("{} returned a List of size: {}", sp.getNamedQuery(), result.size()); } return result; }
/** * Method validates GenericGenerator.strategy. Generator strategy either a predefined Hibernate * strategy or a fully qualified class name. * * @param messages * @param reporter * @param astRoot */ protected void validateStrategy( List<IMessage> messages, IReporter reporter, CompilationUnit astRoot) { if (this.strategy != null) { TextRange range = getStrategyTextRange(astRoot) == null ? TextRange.Empty.instance() : getStrategyTextRange(astRoot); if (this.strategy.trim().length() == 0) { messages.add( HibernateJpaValidationMessage.buildMessage( IMessage.HIGH_SEVERITY, STRATEGY_CANT_BE_EMPTY, getResource(), range)); } else if (!generatorClasses.contains(this.strategy)) { IType lwType = null; try { lwType = getJpaProject().getJavaProject().findType(this.strategy); if (lwType == null || !lwType.isClass()) { messages.add( HibernateJpaValidationMessage.buildMessage( IMessage.HIGH_SEVERITY, STRATEGY_CLASS_NOT_FOUND, new String[] {this.strategy}, getResource(), range)); } else { if (!JpaUtil.isTypeImplementsInterface( getJpaProject().getJavaProject(), lwType, "org.hibernate.id.IdentifierGenerator")) { //$NON-NLS-1$ messages.add( HibernateJpaValidationMessage.buildMessage( IMessage.HIGH_SEVERITY, STRATEGY_INTERFACE, new String[] {this.strategy}, getResource(), range)); } } } catch (JavaModelException e) { // just ignore it! } } } }
private boolean existsInDatabaseOnAllObjects(Identifiable<?> entity, Map<String, Object> values) { if (entity == null || values == null || values.isEmpty()) { return false; } String entityName = jpaUtil.getEntityName(entity); String sqlQuery = "select count(c) from " + entityName + " c where"; boolean first = true; for (Map.Entry<String, Object> property : values.entrySet()) { sqlQuery += !first ? " and " : " "; if (property.getValue() instanceof String) { sqlQuery += "upper(" + property.getKey() + ")=:" + property.getKey(); } else { sqlQuery += property.getKey() + "=:" + property.getKey(); } first = false; } if (entity.isIdSet()) { if (!first) { sqlQuery += " and"; } sqlQuery += " id<>:id"; } TypedQuery<Long> query = entityManager.createQuery(sqlQuery, Long.class); for (Map.Entry<String, Object> property : values.entrySet()) { String propertyName = property.getKey(); Object value = property.getValue(); if (value instanceof String) { value = ((String) value).toUpperCase(LocaleHolder.getLocale()); } query.setParameter(propertyName, value); } if (entity.isIdSet()) { query.setParameter("id", entity.getId()); } return query.getSingleResult() > 0; }
private String simpleUniqueConstraintError(Identifiable<?> entity, String property) { return WordUtils.uncapitalize(jpaUtil.getEntityName(entity)) + "_" + property + "_already_exists"; }