當前位置: 首頁>>代碼示例>>Java>>正文


Java PersistenceException類代碼示例

本文整理匯總了Java中javax.persistence.PersistenceException的典型用法代碼示例。如果您正苦於以下問題:Java PersistenceException類的具體用法?Java PersistenceException怎麽用?Java PersistenceException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


PersistenceException類屬於javax.persistence包,在下文中一共展示了PersistenceException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getStatistics

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * 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;
    }
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:16,代碼來源:HibernateMetrics.java

示例2: convertRollbackToConflict

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:minijax,項目名稱:minijax,代碼行數:24,代碼來源:DefaultBaseDao.java

示例3: findById

import javax.persistence.PersistenceException; //導入依賴的package包/類
@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);

	}
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:17,代碼來源:ServerServiceImpl.java

示例4: activationAccount

import javax.persistence.PersistenceException; //導入依賴的package包/類
@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());

}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:21,代碼來源:UserServiceImpl.java

示例5: update

import javax.persistence.PersistenceException; //導入依賴的package包/類
@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;
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:21,代碼來源:UserServiceImpl.java

示例6: executeJpqlQuery

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * @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();
    }
}
 
開發者ID:napstr,項目名稱:SqlSauce,代碼行數:24,代碼來源:DatabaseWrapper.java

示例7: findAll

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * 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);
	}
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:23,代碼來源:ApplicationServiceImpl.java

示例8: findCarStationsInRadius

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * 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();
    }
}
 
開發者ID:RWTH-i5-IDSG,項目名稱:xsharing-services-router,代碼行數:35,代碼來源:StationRepositoryImpl.java

示例9: findApplyAndMerge

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * 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();
    }
}
 
開發者ID:napstr,項目名稱:SqlSauce,代碼行數:25,代碼來源:DatabaseWrapper.java

示例10: create

import javax.persistence.PersistenceException; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:20,代碼來源:DeploymentServiceImpl.java

示例11: findByCoordinate

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * 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");
    }
}
 
開發者ID:RWTH-i5-IDSG,項目名稱:xsharing-services-router,代碼行數:29,代碼來源:StationRepositoryImpl.java

示例12: update

import javax.persistence.PersistenceException; //導入依賴的package包/類
@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;
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:21,代碼來源:ImageServiceImpl.java

示例13: remove

import javax.persistence.PersistenceException; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:21,代碼來源:ImageServiceImpl.java

示例14: findSharingStation

import javax.persistence.PersistenceException; //導入依賴的package包/類
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;
    }
}
 
開發者ID:RWTH-i5-IDSG,項目名稱:xsharing-services-router,代碼行數:19,代碼來源:StationRepositoryImpl.java

示例15: cancelBooking

import javax.persistence.PersistenceException; //導入依賴的package包/類
/**
 * 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;
    }
}
 
開發者ID:maillouxc,項目名稱:git-rekt,代碼行數:32,代碼來源:BookingService.java


注:本文中的javax.persistence.PersistenceException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。