Java 类javax.persistence.PersistenceException 实例源码

项目:minijax    文件:DefaultBaseDao.java   
/**
 * Converts a JPA rollback exception into a conflict exception.
 *
 * @param ex The database rollback exception.
 * @return A structured key/value conflict exception.
 */
private static ConflictException convertRollbackToConflict(final PersistenceException ex) {
    final List<Pattern> patterns = Arrays.asList(
            Pattern.compile("Duplicate entry '(?<value>[^']+)' for key '(?<key>[^']+)'"),
            Pattern.compile("CONSTRAINT_INDEX_[a-zA-Z0-9_]+ ON PUBLIC\\.[a-zA-Z]+\\((?<key>[a-zA-Z]+)\\) VALUES \\('(?<value>[^']+)'"));

    for (final Pattern pattern : patterns) {
        final Matcher matcher = pattern.matcher(ex.getMessage());
        if (matcher.find()) {
            final String key = matcher.group("key").toLowerCase();
            final String value = matcher.group("value");
            return new ConflictException(key, value);
        }
    }

    LOG.warn("Unrecognized RollbackException: {}", ex.getMessage(), ex);
    throw ex;
}
项目:devops-cstack    文件:ServerServiceImpl.java   
@Override
public Server findById(Integer id) throws ServiceException {
    try {
        logger.debug("findById : Methods parameters : " + id);
        Server server = serverDAO.findOne(id);
        if (server != null) {
            logger.info("Server with id " + id + " found!");
            logger.info("" + server);
        }
        return server;
    } catch (PersistenceException e) {
        logger.error("Error ServerService : error findById Method : " + e);
        throw new ServiceException("Error database :  " + e.getLocalizedMessage(), e);

    }
}
项目:devops-cstack    文件:UserServiceImpl.java   
@Override
@Transactional
public void activationAccount(User user)
        throws ServiceException {
    try {
        logger.debug("UserService : User " + user.toString());

        user = userDAO.findOne(user.getId());
        user.setStatus(User.STATUS_ACTIF);
        user = userDAO.saveAndFlush(user);

    } catch (PersistenceException e) {
        logger.error("UserService Error : Activate User Account" + e);
        throw new ServiceException(e.getLocalizedMessage(), e);
    }

    logger.info("UserService : User " + user.getLastName()
            + " account activated - status = " + user.getStatus());

}
项目:devops-cstack    文件:UserServiceImpl.java   
@Override
@Transactional
public User update(User user)
        throws ServiceException {

    logger.debug("update : Methods parameters : " + user.toString());
    logger.info("UserService : Starting updating user "
            + user.getLastName());
    try {
        userDAO.saveAndFlush(user);
    } catch (PersistenceException e) {
        logger.error("UserService Error : update User" + e);
        throw new ServiceException(e.getLocalizedMessage(), e);
    }

    logger.info("UserService : User " + user.getLogin()
            + " successfully updated.");

    return user;
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * @return the number of entities updated or deleted
 */
public int executeJpqlQuery(@Nonnull final String queryString, @Nullable final Map<String, Object> parameters)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query query = em.createQuery(queryString);
        if (parameters != null) {
            parameters.forEach(query::setParameter);
        }
        em.getTransaction().begin();
        final int updatedOrDeleted = query.executeUpdate();
        em.getTransaction().commit();
        return updatedOrDeleted;
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to execute JPQL query %s with %s parameters on DB %s",
                queryString, parameters != null ? parameters.size() : "null", this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
项目:devops-cstack    文件:ApplicationServiceImpl.java   
/**
 * Method useful for Logs and Monitoring Management
 *
 * @return
 * @throws ServiceException
 */
@Override
public List<Application> findAll() throws ServiceException {
    try {
        logger.debug("start findAll");
        List<Application> listApplications = applicationDAO.findAll();
        for (Application application : listApplications) {
            application.setServer(serverService.findByApp(application));
            application.setModules(moduleService.findByAppAndUser(application.getUser(), application.getName()));
        }
        logger.debug("ApplicationService : All Applications found ");
        return listApplications;
    } catch (PersistenceException e) {
        logger.error("Error ApplicationService : error findAll Method : " + e);
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}
项目:xsharing-services-router    文件:StationRepositoryImpl.java   
/**
 * Spatial selection of CarStation entity using circle around target point
 * NOTE: the \\ notation is required for escaping the query
 *
 * @param targetX X coordinate of the target location (longitude)
 * @param targetY Y coordinate of the target location (latitude)
 * @param radius  Radius around target in meters
 * @return List of CarStation entities in range
 */
@Override
public List<CarStation> findCarStationsInRadius(Double targetX, Double targetY, Double radius) {
    String sql = "WITH index_sel AS (" +
            "SELECT s.*, st_distance(st_geomfromtext('POINT(' || ? || ' ' || ? || ')', 4326)" +
            "\\:\\:GEOGRAPHY, s.geopos\\:\\:GEOGRAPHY) AS distance " +
            "FROM carstation s " +
            "ORDER BY st_geomfromtext('POINT(' || ? || ' ' || ? || ')', 4326) <-> s.geopos) " +
            "SELECT " + getStationFieldsConcat() +
            "FROM index_sel " +
            "WHERE distance < ? ORDER BY distance;";

    Query query = entityManager.createNativeQuery(sql, CarStation.class);
    query.setParameter(1, targetX);
    query.setParameter(2, targetY);
    query.setParameter(3, targetX);
    query.setParameter(4, targetY);
    query.setParameter(5, radius);

    try {
        return query.getResultList();
    } catch (PersistenceException e) {
        // Unable to find closest Sharing Station in Database
        return Lists.newArrayList();
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * So you want to load an entity, set some data, and save it again, without detaching it from the persistence
 * context and without bothering with the EntityManager?
 * Look no further! Functional programming to the rescue, just pass a function that does the required transformation
 * on the entity.
 * <p>
 * NOTE that this will create a new instance of the entity if it does not exist yet.
 *
 */
@Nonnull
public <E extends SaucedEntity<I, E>, I extends Serializable> E findApplyAndMerge(@Nonnull final Transfiguration<I, E> transfiguration)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        return this.lockedWrappedTransformFunc(transfiguration).apply(em);
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to find, apply and merge entity id %s of class %s on DB %s",
                transfiguration.key.id.toString(), transfiguration.key.clazz.getName(),
                this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
项目:devops-cstack    文件:DeploymentServiceImpl.java   
@Override
@Transactional
public Deployment create(Application application, DeploymentType deploymentType, String contextPath)
        throws ServiceException, CheckException {
    try {
        Deployment deployment = new Deployment();
        deployment.setApplication(application);
        deployment.setType(deploymentType);
        deployment.setDate(new Date());
        application = applicationService.findByNameAndUser(application
                .getUser(), application.getName());
        application.setDeploymentStatus(Application.ALREADY_DEPLOYED);
        application.setContextPath(contextPath);
        applicationService.saveInDB(application);
        return deploymentDAO.save(deployment);
    } catch (PersistenceException e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}
项目:xsharing-services-router    文件:StationRepositoryImpl.java   
/**
 * Selection of arbitrary sharing stations at specific location via lat/lon coordinates
 *
 * @param lon Longitude of the target location
 * @param lat Latitude of the target location
 * @return A descendant of SharingStation class if exists at target location
 * @throws DatabaseException if no station could be retrieved
 */
@Override
public SharingStation findByCoordinate(Double lon, Double lat, Class<? extends SharingStation> clazz) throws DatabaseException {
    String sql = "SELECT * FROM bikestation WHERE " +
                 "ST_PointFromText('POINT(' || ? || ' ' || ? || ')', 4326) = geopos " +
                 "UNION " +
                 "SELECT * FROM carstation " +
                 "WHERE ST_PointFromText('POINT(' || ? || ' ' || ? || ')', 4326) = geopos;";

    Query q = entityManager.createNativeQuery(sql, clazz);

    q.setParameter(1, lon);
    q.setParameter(2, lat);
    q.setParameter(3, lon);
    q.setParameter(4, lat);
    try {
        return (SharingStation) q.getSingleResult();
    } catch (PersistenceException e) {
        throw new DatabaseException("Unable to find Sharing Station in Database");
    }
}
项目:devops-cstack    文件:ImageServiceImpl.java   
@Override
@Transactional
public Image update(Image image)
        throws ServiceException {

    logger.debug("update : Methods parameters : " + image.toString());
    logger.info("ImageService : Starting updating image " + image.getName());

    try {
        imageDAO.saveAndFlush(image);
    } catch (PersistenceException e) {
        logger.error("ImageService Error : update Image" + e);
        throw new ServiceException(e.getLocalizedMessage(), e);
    }

    logger.info("ImageService : Image " + image.getName()
            + "successfully updated.");

    return image;
}
项目:devops-cstack    文件:ImageServiceImpl.java   
@Override
@Transactional
public void remove(Image image)
        throws ServiceException {
    try {
        logger.debug("remove : Methods parameters : " + image.toString());
        logger.info("Starting removing application " + image.getName());

        imageDAO.delete(image);

        logger.info("ImageService : Image successfully removed ");

    } catch (PersistenceException e) {

        logger.error("ImageService Error : failed to remove "
                + image.getName() + " : " + e);

        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}
项目:xsharing-services-router    文件:StationRepositoryImpl.java   
private SharingStation findSharingStation(String placeId, String providerId) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<SharingStation> s = cb.createQuery(SharingStation.class);
    Root<SharingStation> station = s.from(SharingStation.class);
    s.where(cb.and(
            cb.equal(station.get(SharingStation_.providerId), providerId),
            cb.equal(station.get(SharingStation_.placeId), placeId))
    );
    TypedQuery<SharingStation> query = entityManager.createQuery(s);

    try {
        return query.getSingleResult();
    } catch (PersistenceException e) {
        log.error("Could not find the station {} {} in database although it should exist! ({})", providerId,
                placeId, e.getMessage());
        return null;
    }
}
项目:git-rekt    文件:BookingService.java   
/**
 * Cancels the provided booking, which includes applying the business requirement to assess a
 * cancellation fee on the bill.
 *
 * If provided a booking where the isCanceled field is already set to true, this method simply
 * returns without doing any other work. This behavior can be used to implement custom
 * cancellation logic if desired, and avoids the overhead of having to consult the database to
 * resolve the discrepancy or doing weird stuff to control the field more strictly.
 *
 * @param booking The booking to cancel.
 */
public void cancelBooking(Booking booking) {
    if(booking.isCanceled()) {
        return;
    }
    try {
        entityManager.getTransaction().begin();
        entityManager.merge(booking);
        booking.setCanceled(true);
        double cancellationFee = calcCancellationFee(booking);
        BillItem refund = new BillItem("Refund", booking.getBill().getTotal() * -1, 1);
        booking.getBill().getCharges().add(refund);
        BillItem cancellationCharge = new BillItem("Cancellation fee", cancellationFee, 1);
        booking.getBill().getCharges().add(cancellationCharge);
        sendBookingCancellationEmail(booking);
        entityManager.getTransaction().commit();
    } catch (PersistenceException e) {
        entityManager.getTransaction().rollback();
        throw e;
    }
}
项目:aries-jpa    文件:EMFBuilderServiceResolver.java   
/**
 * This method looks for a matching EntityManagerFactoryBuilder service to create the
 * EMF with.
 */
@Override
public EntityManagerFactory createEntityManagerFactory(String emName, @SuppressWarnings("rawtypes") Map map) {
    for (Entry<ServiceReference<Object>, Object> e : tracker.getTracked().entrySet()) {
        String serviceUnitName = String.valueOf(e.getKey().getProperty("osgi.unit.name"));

        if(serviceUnitName.equals(emName)) {
            try {
                Object emfBuilder = e.getValue();
                Method m = emfBuilder.getClass().getMethod("createEntityManagerFactory", Map.class);
                return (EntityManagerFactory) m.invoke(emfBuilder, map);
            } catch (Exception ex) {
                throw new PersistenceException("Failed to create an EntityManagerFactory for unit " +
                        emName, ex);
            }
        }
    }
    return null;
}
项目:aries-jpa    文件:EMFBuilderServiceResolver.java   
/**
 * This method looks for a matching EntityManagerFactoryBuilder service to create the
 * EMF with.
 */
@Override
public EntityManagerFactory createEntityManagerFactory(String emName, @SuppressWarnings("rawtypes") Map map) {
    for (Entry<ServiceReference<Object>, Object> e : tracker.getTracked().entrySet()) {
        String serviceUnitName = String.valueOf(e.getKey().getProperty("osgi.unit.name"));

        if(serviceUnitName.equals(emName)) {
            try {
                Object emfBuilder = e.getValue();
                Method m = emfBuilder.getClass().getMethod("createEntityManagerFactory", Map.class);
                return (EntityManagerFactory) m.invoke(emfBuilder, map);
            } catch (Exception ex) {
                throw new PersistenceException("Failed to create an EntityManagerFactory for unit " +
                        emName, ex);
            }
        }
    }
    return null;
}
项目:SqlSauce    文件:DatabaseWrapper.java   
public <E extends IEntity<I, E>, I extends Serializable> void deleteEntity(@Nonnull final EntityKey<I, E> entityKey)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        em.getTransaction().begin();
        final IEntity<I, E> entity = em.find(entityKey.clazz, entityKey.id);
        if (entity != null) {
            em.remove(entity);
        }
        em.getTransaction().commit();
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to delete entity id %s of class %s on DB %s",
                entityKey.id.toString(), entityKey.clazz.getName(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
项目:micrometer    文件:HibernateMetrics.java   
/**
 * Get the {@code Statistics} object from the underlying {@code SessionFactory}. If it isn't hibernate that is
 * used return {@code null}.
 *
 * @param emf an {@code EntityManagerFactory}
 * @return the {@code Statistics} from the underlying {@code SessionFactory} or {@code null}.
 */
private Statistics getStatistics(EntityManagerFactory emf) {
    try {
        SessionFactory sf = emf.unwrap(SessionFactory.class);
        return sf.getStatistics();
    } catch (PersistenceException pe) {
        return null;
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * Send a notifications with Postgres' LISTEN/NOTIFY feature.
 * See https://www.postgresql.org/docs/current/static/sql-notify.html for more info.
 * <p>
 * See {@link NotificationService} for a listener implementation provided by this package.
 */
public void notif(@Nonnull String channel, @Nullable String payload) {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        em.getTransaction().begin();
        //the cast is necessary otherwise hibernate chokes on the void return type
        em.createNativeQuery("SELECT cast(pg_notify(:channel, :payload) AS TEXT);")
                .setParameter("channel", channel)
                .setParameter("payload", payload != null ? payload : "")
                .getSingleResult();
        em.getTransaction().commit();
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to execute notification for channel %s with payload %s on DB %s",
                channel, payload, this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
项目:oscm    文件:BillingAdapterDAOIT.java   
@Test(expected = PersistenceException.class)
public void saveDuplicateAdapter() throws Exception {
    // given
    BillingAdapter adapter1 = creatBillingAdapter(
            BillingAdapterIdentifier.NATIVE_BILLING.toString(), true);

    BillingAdapter adapter2 = creatBillingAdapter(BILLING_ID, true);

    // an adapter whose billing id is changed to an existing one
    modifyBillingId(BILLING_ID,
            BillingAdapterIdentifier.NATIVE_BILLING.toString());

    // when
    save(adapter1);
    save(adapter2);
}
项目:oscm    文件:EventServiceBean.java   
/**
 * Tests whether this exception or any nested exception is a
 * {@link EntityExistsException}. Unfortunately {@link EJBException}
 * sometimes nests cause exception in {@link Throwable#getCause()},
 * sometimes in {@link EJBException#getCausedByException()}. Arrrrg.
 */
private boolean isEntityExistsException(final Throwable e) {
    if (e == null) {
        return false;
    }
    if (e instanceof PersistenceException) {
        return true;
    }
    if (e instanceof EJBException) {
        final EJBException ejbex = (EJBException) e;
        if (isEntityExistsException(ejbex.getCausedByException())) {
            return true;
        }
    }
    return isEntityExistsException(e.getCause());
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * Use this for COUNT() and similar sql queries which are guaranteed to return a result
 */
@Nonnull
@CheckReturnValue
public <T> T selectSqlQuerySingleResult(@Nonnull final String queryString,
                                        @Nullable final Map<String, Object> parameters,
                                        @Nonnull final Class<T> resultClass) throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query q = em.createNativeQuery(queryString);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        em.getTransaction().begin();
        final T result = resultClass.cast(q.getSingleResult());
        em.getTransaction().commit();
        return setSauce(result);
    } catch (final PersistenceException | ClassCastException e) {
        final String message = String.format("Failed to select single result plain SQL query %s with %s parameters for class %s on DB %s",
                queryString, parameters != null ? parameters.size() : "null", resultClass.getName(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
项目:lams    文件:JpaTransactionManager.java   
@Override
protected void doRollback(DefaultTransactionStatus status) {
    JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Rolling back JPA transaction on EntityManager [" +
                txObject.getEntityManagerHolder().getEntityManager() + "]");
    }
    try {
        EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
        if (tx.isActive()) {
            tx.rollback();
        }
    }
    catch (PersistenceException ex) {
        throw new TransactionSystemException("Could not roll back JPA transaction", ex);
    }
    finally {
        if (!txObject.isNewEntityManagerHolder()) {
            // Clear all pending inserts/updates/deletes in the EntityManager.
            // Necessary for pre-bound EntityManagers, to avoid inconsistent state.
            txObject.getEntityManagerHolder().getEntityManager().clear();
        }
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * Run a good old SQL query
 *
 * @return the number of entities updated or deleted
 */
public int executeSqlQuery(@Nonnull final String queryString,
                           @Nullable final Map<String, Object> parameters) throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query q = em.createNativeQuery(queryString);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        em.getTransaction().begin();
        int updated = q.executeUpdate();
        em.getTransaction().commit();
        return updated;
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to execute plain SQL query %s with %s parameters on DB %s",
                queryString, parameters != null ? parameters.size() : "null", this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
项目:lams    文件:HibernateJpaDialect.java   
@Override
public Object prepareTransaction(EntityManager entityManager, boolean readOnly, String name)
        throws PersistenceException {

    Session session = getSession(entityManager);
    FlushMode flushMode = session.getFlushMode();
    FlushMode previousFlushMode = null;
    if (readOnly) {
        // We should suppress flushing for a read-only transaction.
        session.setFlushMode(FlushMode.MANUAL);
        previousFlushMode = flushMode;
    }
    else {
        // We need AUTO or COMMIT for a non-read-only transaction.
        if (flushMode.lessThan(FlushMode.COMMIT)) {
            session.setFlushMode(FlushMode.AUTO);
            previousFlushMode = flushMode;
        }
    }
    return new SessionTransactionData(session, previousFlushMode);
}
项目:lams    文件:LocalEntityManagerFactoryBean.java   
/**
 * Initialize the EntityManagerFactory for the given configuration.
 * @throws javax.persistence.PersistenceException in case of JPA initialization errors
 */
@Override
protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException {
    if (logger.isInfoEnabled()) {
        logger.info("Building JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'");
    }
    PersistenceProvider provider = getPersistenceProvider();
    if (provider != null) {
        // Create EntityManagerFactory directly through PersistenceProvider.
        EntityManagerFactory emf = provider.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
        if (emf == null) {
            throw new IllegalStateException(
                    "PersistenceProvider [" + provider + "] did not return an EntityManagerFactory for name '" +
                    getPersistenceUnitName() + "'");
        }
        return emf;
    }
    else {
        // Let JPA perform its standard PersistenceProvider autodetection.
        return Persistence.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
    }
}
项目:lams    文件:EntityClass.java   
private void createDefaultCallback(Class callbackTypeClass,
                                   DotName callbackTypeName,
                                   String callbackClassName,
                                   Map<Class<?>, String> callbacksByClass) {
    for ( AnnotationInstance callback : getLocalBindingContext().getIndex().getAnnotations( callbackTypeName ) ) {
        MethodInfo methodInfo = (MethodInfo) callback.target();
        validateMethod( methodInfo, callbackTypeClass, callbacksByClass, true );
        if ( methodInfo.declaringClass().name().toString().equals( callbackClassName ) ) {
            if ( methodInfo.args().length != 1 ) {
                throw new PersistenceException(
                        String.format(
                                "Callback method %s must have exactly one argument defined as either Object or %s in ",
                                methodInfo.name(),
                                getEntityName()
                        )
                );
            }
            callbacksByClass.put( callbackTypeClass, methodInfo.name() );
        }
    }
}
项目:lams    文件:AttributeConverterSqlTypeDescriptorAdapter.java   
@Override
@SuppressWarnings("unchecked")
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
    // Get the binder for the intermediate type representation
    final ValueBinder realBinder = delegate.getBinder( intermediateJavaTypeDescriptor );
    return new BasicBinder<X>( javaTypeDescriptor, this ) {
        @Override
        @SuppressWarnings("unchecked")
        protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
            final Object convertedValue;
            try {
                convertedValue = converter.convertToDatabaseColumn( value );
            }
            catch (PersistenceException pe) {
                throw pe;
            }
            catch (RuntimeException re) {
                throw new PersistenceException( "Error attempting to apply AttributeConverter", re );
            }
            realBinder.bind( st, convertedValue, index, options );
        }
    };
}
项目:SqlSauce    文件:DatabaseConnection.java   
/**
 * @return true if the test query was successful and false if not
 */
@CheckReturnValue
public boolean runTestQuery() {
    final EntityManager em = this.emf.createEntityManager();
    try {
        em.getTransaction().begin();
        em.createNativeQuery(TEST_QUERY).getResultList();
        em.getTransaction().commit();
        return true;
    } catch (final PersistenceException e) {
        log.error("Test query failed", e);
        return false;
    } finally {
        em.close();
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * @return An entity if it exists in the database or null if it doesn't exist. If the entity is a SaucedEntity the
 * sauce will be set.
 */
@Nullable
@CheckReturnValue
public <E extends IEntity<I, E>, I extends Serializable> E getEntity(@Nonnull final EntityKey<I, E> entityKey)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        em.getTransaction().begin();
        @Nullable final E result = em.find(entityKey.clazz, entityKey.id);
        em.getTransaction().commit();
        return setSauce(result);
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to find entity of class %s for id %s on DB %s",
                entityKey.clazz.getName(), entityKey.id.toString(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
@Nonnull
@CheckReturnValue
private <T> List<T> selectSqlQuery(@Nonnull final Function<EntityManager, Query> queryFunc,
                                   @Nullable final Map<String, Object> parameters)
        throws DatabaseException, PersistenceException, ClassCastException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query q = queryFunc.apply(em);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        return selectNativeSqlQuery(em, q);
    } finally {
        em.close();
    }
}
项目:springboot-shiro-cas-mybatis    文件:JpaLockingStrategy.java   
/**
 * Acquire the lock object.
 *
 * @param em the em
 * @param lock the lock
 * @return true, if successful
 */
private boolean acquire(final EntityManager em, final Lock lock) {
    lock.setUniqueId(uniqueId);
    if (lockTimeout > 0) {
        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, lockTimeout);
        lock.setExpirationDate(cal.getTime());
    } else {
        lock.setExpirationDate(null);
    }
    boolean success = false;
    try {
        if (lock.getApplicationId() != null) {
            em.merge(lock);
        } else {
            lock.setApplicationId(applicationId);
            em.persist(lock);
        }
        success = true;
    } catch (final PersistenceException e) {
        success = false;
        if (logger.isDebugEnabled()) {
            logger.debug("{} could not obtain {} lock.", uniqueId, applicationId, e);
        } else {
            logger.info("{} could not obtain {} lock.", uniqueId, applicationId);
        }
    }
    return success;
}
项目:git-rekt    文件:EmployeeService.java   
/**
 * Removes the provided employee from the database.
 *
 * This operation cannot be undone, so be sure this is what you want to do.
 *
 * @param employee The employee to delete.
 */
public void deleteEmployee(Employee e){
    try {
        entityManager.getTransaction().begin();
        entityManager.remove(entityManager.merge(e));
        entityManager.getTransaction().commit();
    } catch (PersistenceException ex) {
        entityManager.getTransaction().rollback();
        throw ex;
    }
}
项目:springboot-shiro-cas-mybatis    文件:JpaLockingStrategy.java   
/**
 * Acquire the lock object.
 *
 * @param em the em
 * @param lock the lock
 * @return true, if successful
 */
private boolean acquire(final EntityManager em, final Lock lock) {
    lock.setUniqueId(uniqueId);
    if (lockTimeout > 0) {
        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, lockTimeout);
        lock.setExpirationDate(cal.getTime());
    } else {
        lock.setExpirationDate(null);
    }
    boolean success = false;
    try {
        if (lock.getApplicationId() != null) {
            em.merge(lock);
        } else {
            lock.setApplicationId(applicationId);
            em.persist(lock);
        }
        success = true;
    } catch (final PersistenceException e) {
        success = false;
        if (logger.isDebugEnabled()) {
            logger.debug("{} could not obtain {} lock.", uniqueId, applicationId, e);
        } else {
            logger.info("{} could not obtain {} lock.", uniqueId, applicationId);
        }
    }
    return success;
}
项目:devops-cstack    文件:MessageServiceImpl.java   
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Message create(Message message)
        throws ServiceException {
    try {
        message.setCuInstanceName(cuInstanceName);
        return messageDAO.save(message);
    } catch (PersistenceException e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}
项目:devops-cstack    文件:MessageServiceImpl.java   
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void delete(Message message)
        throws ServiceException {
    try {
        messageDAO.delete(message);
    } catch (PersistenceException e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}
项目:query-search    文件:SearchService.java   
public default List<?> search(JpqlFilter filter) {
    Objects.requireNonNull(filter, "jpqlFilter is required");

    try {
        return getRepository().search(filter);
    } catch (PersistenceException e) {
        throw new PersistenceException(e);
    }
}
项目:git-rekt    文件:GuestFeedbackService.java   
public void createNewGuestFeedback(GuestFeedback feedback) {
    try {
        entityManager.getTransaction().begin();
        entityManager.persist(feedback);
        entityManager.getTransaction().commit();
    } catch (PersistenceException e) {
        entityManager.getTransaction().rollback();
        throw e;
    }
}
项目:devops-cstack    文件:MessageServiceImpl.java   
@Override
public List<Message> listByApp(User user, String applicationName,
                               int nbMessages)
        throws ServiceException {
    try {
        Pageable pageable = new PageRequest(0, nbMessages,
                sortByLastNameAsc());
        Page<Message> requestedPage = messageDAO.listByApp(user,
                applicationName, cuInstanceName, pageable);
        return requestedPage.getContent();
    } catch (PersistenceException e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}
项目:minijax    文件:DefaultBaseDao.java   
/**
 * Inserts a new instance in the database.
 *
 * @param obj The object to create.
 * @return The instance with ID.
 */
@Override
public <T extends BaseEntity> T create(final T obj) {
    try {
        em.getTransaction().begin();
        em.persist(obj);
        em.getTransaction().commit();
        return obj;
    } catch (final PersistenceException ex) {
        throw convertRollbackToConflict(ex);
    }
}