本文整理汇总了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;
}
}
示例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;
}
示例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);
}
}
示例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());
}
示例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;
}
示例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();
}
}
示例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);
}
}
示例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();
}
}
示例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();
}
}
示例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);
}
}
示例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");
}
}
示例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;
}
示例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);
}
}
示例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;
}
}
示例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;
}
}