下面列出了怎么用javax.persistence.PersistenceException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
throws PersistenceException, SQLException, TransactionException {
OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager);
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
// Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration
FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan();
if (fetchPlan instanceof JDBCFetchPlan) {
IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel());
((JDBCFetchPlan) fetchPlan).setIsolation(isolation);
}
}
entityManager.getTransaction().begin();
if (!definition.isReadOnly()) {
// Like with EclipseLink, make sure to start the logic transaction early so that other
// participants using the connection (such as JdbcTemplate) run in a transaction.
openJpaEntityManager.beginStore();
}
// Custom implementation for OpenJPA savepoint handling
return new OpenJpaTransactionData(openJpaEntityManager);
}
@Override
public void afterPropertiesSet() throws PersistenceException {
PersistenceUnitManager managerToUse = this.persistenceUnitManager;
if (this.persistenceUnitManager == null) {
this.internalPersistenceUnitManager.afterPropertiesSet();
managerToUse = this.internalPersistenceUnitManager;
}
this.persistenceUnitInfo = determinePersistenceUnitInfo(managerToUse);
JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter();
if (jpaVendorAdapter != null && this.persistenceUnitInfo instanceof SmartPersistenceUnitInfo) {
String rootPackage = jpaVendorAdapter.getPersistenceProviderRootPackage();
if (rootPackage != null) {
((SmartPersistenceUnitInfo) this.persistenceUnitInfo).setPersistenceProviderPackageName(rootPackage);
}
}
super.afterPropertiesSet();
}
@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();
}
}
}
@SuppressWarnings("deprecation")
@Nullable
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
FlushMode flushMode = (FlushMode) ReflectionUtils.invokeMethod(getFlushMode, session);
Assert.state(flushMode != null, "No FlushMode from Session");
if (readOnly) {
// We should suppress flushing for a read-only transaction.
if (!flushMode.equals(FlushMode.MANUAL)) {
session.setFlushMode(FlushMode.MANUAL);
return flushMode;
}
}
else {
// We need AUTO or COMMIT for a non-read-only transaction.
if (flushMode.lessThan(FlushMode.COMMIT)) {
session.setFlushMode(FlushMode.AUTO);
return flushMode;
}
}
// No FlushMode change needed...
return null;
}
public void createOrganization(Organization pOrganization) throws OrganizationAlreadyExistsException, CreationException {
try {
//the EntityExistsException is thrown only when flush occurs
if (pOrganization.getName().trim().equals(""))
throw new CreationException();
em.persist(pOrganization);
em.flush();
} catch (EntityExistsException pEEEx) {
throw new OrganizationAlreadyExistsException(pOrganization);
} catch (PersistenceException pPEx) {
//EntityExistsException is case sensitive
//whereas MySQL is not thus PersistenceException could be
//thrown instead of EntityExistsException
throw new CreationException();
}
}
@Test
public void saveDoesntAllowNullEncodedPayload() {
EncryptedTransaction encryptedTransaction = new EncryptedTransaction();
encryptedTransaction.setHash(new MessageHash(new byte[] {5}));
final Throwable throwable =
catchThrowable(
() -> {
encryptedTransactionDAO.save(encryptedTransaction);
entityManager.flush();
});
assertThat(throwable)
.isInstanceOf(PersistenceException.class)
.hasMessageContaining("integrity constraint violation: NOT NULL check constraint");
}
@Override
public BankOrder save(BankOrder entity) {
try {
BankOrderService bankOrderService = Beans.get(BankOrderService.class);
bankOrderService.generateSequence(entity);
bankOrderService.setSequenceOnBankOrderLines(entity);
if (entity.getStatusSelect() == BankOrderRepository.STATUS_DRAFT) {
bankOrderService.updateTotalAmounts(entity);
}
return super.save(entity);
} catch (Exception e) {
throw new PersistenceException(e.getLocalizedMessage());
}
}
public void createDocM(DocumentMaster pDocumentMaster) throws DocumentMasterAlreadyExistsException, CreationException {
try {
//the EntityExistsException is thrown only when flush occurs
em.persist(pDocumentMaster);
em.flush();
} catch (EntityExistsException pEEEx) {
LOGGER.log(Level.FINER,null,pEEEx);
throw new DocumentMasterAlreadyExistsException(pDocumentMaster);
} catch (PersistenceException pPEx) {
//EntityExistsException is case sensitive
//whereas MySQL is not thus PersistenceException could be
//thrown instead of EntityExistsException
LOGGER.log(Level.FINER,null,pPEx);
throw new CreationException();
}
}
@Ignore
@Test(expected = PersistenceException.class)
public void testDeleteStorageConstraintViolation() throws Exception
{
// Create a storage unit entity that refers to a newly created storage.
final StorageUnitEntity storageUnitEntity = storageUnitDaoTestHelper
.createStorageUnitEntity(STORAGE_NAME, BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE,
SUBPARTITION_VALUES, DATA_VERSION, LATEST_VERSION_FLAG_SET, BDATA_STATUS, STORAGE_UNIT_STATUS, NO_STORAGE_DIRECTORY_PATH);
executeWithoutLogging(SqlExceptionHelper.class, new Command()
{
@Override
public void execute()
{
// Delete the storage which is invalid because there still exists a storage unit entity that references it.
StorageKey alternateKey = new StorageKey(storageUnitEntity.getStorage().getName());
storageService.deleteStorage(alternateKey);
}
});
}
public void createQuery(Query query) throws CreationException, QueryAlreadyExistsException {
try {
QueryRule queryRule = query.getQueryRule();
if (queryRule != null) {
persistQueryRules(queryRule);
}
QueryRule pathDataQueryRule = query.getPathDataQueryRule();
if (pathDataQueryRule != null) {
persistQueryRules(pathDataQueryRule);
}
em.persist(query);
em.flush();
persistContexts(query, query.getContexts());
} catch (EntityExistsException pEEEx) {
LOGGER.log(Level.FINEST, null, pEEEx);
throw new QueryAlreadyExistsException(query);
} catch (PersistenceException pPEx) {
LOGGER.log(Level.FINEST, null, pPEx);
throw new CreationException();
}
}
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
if (contextData == null) {
return null;
}
try {
final JsonNodeFactory factory = OBJECT_MAPPER.getNodeFactory();
final ObjectNode root = factory.objectNode();
contextData.forEach(new BiConsumer<String, Object>() {
@Override
public void accept(final String key, final Object value) {
// we will cheat here and write the toString of the Object... meh, but ok.
root.put(key, String.valueOf(value));
}
});
return OBJECT_MAPPER.writeValueAsString(root);
} catch (final Exception e) {
throw new PersistenceException("Failed to convert contextData to JSON string.", e);
}
}
public static PersistenceUnitTransactionType interpretTransactionType(Object value) {
if ( value == null ) {
return null;
}
if ( PersistenceUnitTransactionType.class.isInstance( value ) ) {
return (PersistenceUnitTransactionType) value;
}
final String stringValue = value.toString();
if ( StringHelper.isEmpty( stringValue ) ) {
return null;
}
else if ( stringValue.equalsIgnoreCase( "JTA" ) ) {
return PersistenceUnitTransactionType.JTA;
}
else if ( stringValue.equalsIgnoreCase( "RESOURCE_LOCAL" ) ) {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
else {
throw new PersistenceException( "Unknown TransactionType: " + stringValue );
}
}
/**
* Tests finding all circle entities when there is an error occurring in the repository.
* Expected result:
* There should be a flux returned from the service.
* There should be an error from the mono containing an entity not found exception.
*/
@Test
public void findAllPersistenceErrorTest() {
/* Set up repository mock as to generate error when find is attempted. */
Mockito
.when(mServiceRepository.findAll())
.thenThrow(PersistenceException.class);
/* Attempt the find. */
final Flux<Circle> theFoundCirclesFlux = mServiceUnderTest.findAll();
/* Verify that there is an error from the returned mono containing an exception . */
StepVerifier
.create(theFoundCirclesFlux)
.expectError(PersistenceException.class)
.verify();
}
@Test
public void shouldProhibitDeletionOfNonTemporaryBuild() {
// given
int brId = 666;
BuildRecord br = prepareBuildRecordBuilder().id(brId).temporaryBuild(false).build();
em.getTransaction().begin();
em.persist(br);
em.getTransaction().commit();
// when, then
try {
em.getTransaction().begin();
em.remove(br);
em.getTransaction().commit();
} catch (PersistenceException ex) {
em.getTransaction().rollback();
BuildRecord obtainedBr = em.find(BuildRecord.class, brId);
assertNotNull(obtainedBr);
assertEquals(brId, obtainedBr.getId().intValue());
return;
}
fail("Deletion of the standard BuildRecord should be prohibited.");
}
@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();
}
}
}
public void createPathToPathLink(PathToPathLink pPathToPathLink) throws CreationException, PathToPathLinkAlreadyExistsException {
try {
//the EntityExistsException is thrown only when flush occurs
em.persist(pPathToPathLink);
em.flush();
} catch (EntityExistsException pEEEx) {
LOGGER.log(Level.FINEST,null,pEEEx);
throw new PathToPathLinkAlreadyExistsException(pPathToPathLink);
} catch (PersistenceException pPEx) {
LOGGER.log(Level.FINEST,null,pPEx);
//EntityExistsException is case sensitive
//whereas MySQL is not thus PersistenceException could be
//thrown instead of EntityExistsException
throw new CreationException();
}
}
@Test
public void saveDoesntAllowNullEncryptedKey() {
EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction();
encryptedRawTransaction.setHash(new MessageHash(new byte[] {5}));
encryptedRawTransaction.setEncryptedPayload(new byte[] {5});
encryptedRawTransaction.setNonce("nonce".getBytes());
encryptedRawTransaction.setSender("from".getBytes());
final Throwable throwable =
catchThrowable(
() -> {
encryptedRawTransactionDAO.save(encryptedRawTransaction);
entityManager.flush();
});
assertThat(throwable)
.isInstanceOf(PersistenceException.class)
.hasMessageContaining("NOT NULL constraint failed");
}
protected PersistenceException persistenceException(String message, Exception cause) {
// Provide a comprehensible message if there is an issue with SSL support
Throwable t = cause;
while (t != null) {
if (t instanceof NoSuchAlgorithmException) {
message += "Unable to enable SSL support. You might be in the case where you used the `quarkus.ssl.native=false` configuration"
+ " and SSL was not disabled automatically for your driver.";
break;
}
if (t instanceof CommandAcceptanceException) {
message = "Invalid import file. Make sure your statements are valid and properly separated by a semi-colon.";
break;
}
t = t.getCause();
}
return new PersistenceException(getExceptionHeader() + message, cause);
}
/**
* 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());
}
}
/**
* 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.isDebugEnabled()) {
logger.debug("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());
}
}
@Override
public AccountingReport save(AccountingReport accountingReport) {
try {
if (accountingReport.getRef() == null) {
String seq = accountingReportService.getSequence(accountingReport);
accountingReportService.setSequence(accountingReport, seq);
}
return super.save(accountingReport);
} catch (Exception e) {
JPA.em().getTransaction().rollback();
JPA.runInTransaction(() -> TraceBackService.trace(e));
JPA.em().getTransaction().begin();
throw new PersistenceException(e.getLocalizedMessage());
}
}
public static String extractExceptionMessage(Exception e) {
if (e instanceof UndeclaredThrowableException) {
Throwable cause = ((UndeclaredThrowableException) e).getUndeclaredThrowable().getCause();
if (cause instanceof PersistenceException) {
cause = ((PersistenceException) cause).getCause();
if (cause instanceof DataException) {
return ((DataException) cause).getSQLException().getMessage();
}else if(cause instanceof SQLGrammarException) {
return ((SQLGrammarException) cause).getSQLException().getMessage();
}
}
}
return e.getMessage();
}
@Test(expected = PersistenceException.class)
public void testCreateWithDuplicateEmail() {
User user1 = new User("[email protected]", "password", "John Doe");
user1.save();
User user2 = new User("[email protected]", "password", "John Doe");
user2.save();
}
@Override
public Response toResponse(PersistenceException exception) {
if (exception.getCause() instanceof ConstraintViolationException) {
return ResponseFactory
.response(Response.Status.CONFLICT, new ErrorResponse(Response.Status.CONFLICT.getStatusCode(), Messages.CONFLICT_MESSAGE));
}
logger.error("Error: ", exception);
return ResponseFactory
.response(Response.Status.INTERNAL_SERVER_ERROR, new ErrorResponse(exception.getMessage()));
}
@Override
public List<IAccessTokenInfo> invalidateTokensForUser(IUser user) {
EntityManager em = emf.createEntityManager();
TypedQuery<TokenEntity> query = em.createNamedQuery("findTokenEntityByUsername", TokenEntity.class);
query.setParameter("username", user.getName());
List<TokenEntity> resultList = query.getResultList();
List<IAccessTokenInfo> result = new LinkedList<>();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
for (TokenEntity te : resultList)
{
em.remove(te);
result.add(te);
}
em.flush();
tx.commit();
LOGGER.debug("tokens for user {} invalidated", user.getName());
} catch (PersistenceException ex) {
LOGGER.error("persistence error", ex);
tx.rollback();
throw ex;
} finally {
em.close();
}
return result;
}
private static List<PersistenceUnitDescriptor> convertPersistenceUnits(
final List<ParsedPersistenceXmlDescriptor> parsedPersistenceXmlDescriptors) {
try {
return parsedPersistenceXmlDescriptors.stream().map(LightPersistenceXmlDescriptor::new)
.collect(Collectors.toList());
} catch (Exception e) {
throw new PersistenceException("Unable to locate persistence units", e);
}
}
@Override
public Object prepareTransaction(EntityManager entityManager, boolean readOnly, String name)
throws PersistenceException {
Session session = getSession(entityManager);
FlushMode previousFlushMode = prepareFlushMode(session, readOnly);
return new SessionTransactionData(session, previousFlushMode, null, null);
}
/**
* {@inheritDoc}
*/
@Override
@Transactional
public void delete(final Object dataObject) {
doWithExceptionTranslation(new Callable<Object>() {
@Override
public Object call() {
verifyDataObjectWritable(dataObject);
// If the L2 cache is enabled, the item will still be served from the cache
// So, we need to flush that as well for the given type and key
if (sharedEntityManager.getEntityManagerFactory().getCache() != null) {
try {
Object dataObjectKey = sharedEntityManager.getEntityManagerFactory().getPersistenceUnitUtil()
.getIdentifier(dataObject);
if (dataObjectKey != null) {
sharedEntityManager.getEntityManagerFactory().getCache()
.evict(dataObject.getClass(), dataObjectKey);
}
} catch (PersistenceException ex) {
// JPA fails if it can't create the key field classes - we just need to catch and ignore here
}
}
Object mergedDataObject = sharedEntityManager.merge(dataObject);
sharedEntityManager.remove(mergedDataObject);
return null;
}
});
}
/**
* This implementation invokes the standard JPA {@code Transaction.begin}
* method. Throws an InvalidIsolationLevelException if a non-default isolation
* level is set.
* <p>This implementation does not return any transaction data Object, since there
* is no state to be kept for a standard JPA transaction. Hence, subclasses do not
* have to care about the return value ({@code null}) of this implementation
* and are free to return their own transaction data Object.
* @see javax.persistence.EntityTransaction#begin
* @see org.springframework.transaction.InvalidIsolationLevelException
* @see #cleanupTransaction
*/
@Override
@Nullable
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
throws PersistenceException, SQLException, TransactionException {
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
throw new InvalidIsolationLevelException(getClass().getSimpleName() +
" does not support custom isolation levels due to limitations in standard JPA. " +
"Specific arrangements may be implemented in custom JpaDialect variants.");
}
entityManager.getTransaction().begin();
return null;
}
/**
* This implementation always returns {@code null},
* indicating that no JDBC Connection can be provided.
*/
@Override
public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly)
throws PersistenceException, SQLException {
return null;
}