本文整理了Java中javax.persistence.EntityManager.getTransaction()
方法的一些代码示例,展示了EntityManager.getTransaction()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。EntityManager.getTransaction()
方法的具体详情如下:
包路径:javax.persistence.EntityManager
类名称:EntityManager
方法名:getTransaction
[英]Return the resource-level EntityTransaction
object. The EntityTransaction
instance may be used serially to begin and commit multiple transactions.
[中]返回资源级别EntityTransaction
对象。EntityTransaction
实例可连续用于开始和提交多个事务。
代码示例来源:origin: spring-projects/spring-framework
@Override
public void afterCommit() {
super.afterCommit();
// Trigger commit here to let exceptions propagate to the caller.
try {
this.entityManager.getTransaction().commit();
}
catch (RuntimeException ex) {
throw convertException(ex);
}
}
代码示例来源:origin: spring-projects/spring-framework
/**
* 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;
}
代码示例来源:origin: stackoverflow.com
public class ProjectServlet extends HttpServlet {
@EJB ProjectService bean;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// ...
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
bean.assignEmployeeToProject(projectId, empId);
bean.updateProjectStatistics();
} finally {
tx.commit();
}
} catch (Exception e) {
// handle exceptions from EntityTransaction methods
// ...
}
// ...
}
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void testTransactionCommitWithExtendedEntityManagerUnsynchronized() {
given(manager.getTransaction()).willReturn(tx);
tt.execute(status -> {
bean.extendedEntityManagerUnsynchronized.flush();
return null;
});
verify(tx).commit();
verify(manager).flush();
verify(manager).close();
}
代码示例来源:origin: spring-projects/spring-framework
!target.getTransaction().isActive())) {
throw new TransactionRequiredException("No EntityManager with actual transaction available " +
"for current thread - cannot reliably process '" + method.getName() + "' call");
logger.debug("Creating new EntityManager for shared EntityManager invocation");
target = (!CollectionUtils.isEmpty(this.properties) ?
this.targetFactory.createEntityManager(this.properties) :
this.targetFactory.createEntityManager());
isNewEm = true;
代码示例来源:origin: stackoverflow.com
public void uniqueKey() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("default");
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
ValidatorContext validatorContext = validatorFactory.usingContext();
validatorContext.constraintValidatorFactory(new ConstraintValidatorFactoryImpl(entityManagerFactory));
Validator validator = validatorContext.getValidator();
EntityManager em = entityManagerFactory.createEntityManager();
User se = new User("abc", poizon);
Set<ConstraintViolation<User>> violations = validator.validate(se);
System.out.println("Size:- " + violations.size());
em.getTransaction().begin();
em.persist(se);
em.getTransaction().commit();
User se1 = new User("abc");
violations = validator.validate(se1);
System.out.println("Size:- " + violations.size());
}
代码示例来源:origin: Activiti/Activiti
public EntityManager getEntityManager() {
if (entityManager == null) {
entityManager = getEntityManagerFactory().createEntityManager();
if (handleTransactions) {
// Add transaction listeners, if transactions should be handled
TransactionListener jpaTransactionCommitListener = new TransactionListener() {
public void execute(CommandContext commandContext) {
if (isTransactionActive()) {
entityManager.getTransaction().commit();
}
}
};
TransactionListener jpaTransactionRollbackListener = new TransactionListener() {
public void execute(CommandContext commandContext) {
if (isTransactionActive()) {
entityManager.getTransaction().rollback();
}
}
};
TransactionContext transactionContext = Context.getTransactionContext();
transactionContext.addTransactionListener(TransactionState.COMMITTED, jpaTransactionCommitListener);
transactionContext.addTransactionListener(TransactionState.ROLLED_BACK, jpaTransactionRollbackListener);
// Also, start a transaction, if one isn't started already
if (!isTransactionActive()) {
entityManager.getTransaction().begin();
}
}
}
return entityManager;
}
代码示例来源:origin: stackoverflow.com
em = emf.createEntityManager();
em.getTransaction().begin();
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
em.close();
try {
ChangeEntry entry = new ChangeEntry();
em.persist(entry);
fail("Expected ConstraintViolationException wasn't thrown.");
} catch (ConstraintViolationException e) {
try {
ChangeEntryDetails details = new ChangeEntryDetails();
em.persist(details);
fail("Expected ConstraintViolationException wasn't thrown.");
} catch (ConstraintViolationException e) {
ChangeEntryDetails details = new ChangeEntryDetails();
entry.addDetails(details);
em.persist(entry);
代码示例来源:origin: hibernate/hibernate-orm
@Test
@TestForIssue(jiraKey = "HHH-12138")
public void testStoredProcedureReturnValue() {
EntityManager entityManager = createEntityManager();
entityManager.getTransaction().begin();
try {
Integer phoneCount = (Integer) entityManager
.createNativeQuery( "SELECT fn_count_phones(:personId) FROM SYS.DUMMY" )
.setParameter( "personId", 1 )
.getSingleResult();
assertEquals( Integer.valueOf( 2 ), phoneCount );
}
finally {
entityManager.getTransaction().rollback();
entityManager.close();
}
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void testTransactionCommitWithPrebound() {
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<>();
l.add("test");
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
try {
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
assertTrue(TransactionSynchronizationManager.hasResource(factory));
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
return l;
}
});
assertSame(l, result);
assertTrue(TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
}
finally {
TransactionSynchronizationManager.unbindResource(factory);
}
verify(tx).begin();
verify(tx).commit();
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void testTransactionRollbackOnly() {
given(manager.getTransaction()).willReturn(tx);
given(tx.isActive()).willReturn(true);
final List<String> l = new ArrayList<>();
l.add("test");
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
assertTrue(TransactionSynchronizationManager.hasResource(factory));
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
status.setRollbackOnly();
return l;
}
});
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
verify(manager).flush();
verify(tx).rollback();
verify(manager).close();
}
代码示例来源:origin: hibernate/hibernate-orm
try {
entityManager = properties == null ?
factorySupplier.get().createEntityManager():
factorySupplier.get().createEntityManager(properties);
function.beforeTransactionCompletion();
txn = entityManager.getTransaction();
txn.begin();
result = function.apply( entityManager );
txn.commit();
function.afterTransactionCompletion();
if ( entityManager != null ) {
entityManager.close();
代码示例来源:origin: spring-projects/spring-framework
@Test
public void testTransactionCommitWithSharedEntityManager() {
given(manager.getTransaction()).willReturn(tx);
tt.execute(status -> {
bean.sharedEntityManager.flush();
return null;
});
verify(tx).commit();
verify(manager).flush();
verify(manager).close();
}
代码示例来源:origin: org.springframework/spring-orm
!target.getTransaction().isActive())) {
throw new TransactionRequiredException("No EntityManager with actual transaction available " +
"for current thread - cannot reliably process '" + method.getName() + "' call");
logger.debug("Creating new EntityManager for shared EntityManager invocation");
target = (!CollectionUtils.isEmpty(this.properties) ?
this.targetFactory.createEntityManager(this.properties) :
this.targetFactory.createEntityManager());
isNewEm = true;
代码示例来源:origin: camunda/camunda-bpm-platform
public EntityManager getEntityManager() {
if (entityManager == null) {
entityManager = getEntityManagerFactory().createEntityManager();
entityManager.getTransaction().begin();
代码示例来源:origin: spring-projects/spring-framework
/**
* Enlist this application-managed EntityManager in the current transaction.
*/
private void enlistInCurrentTransaction() {
// Resource local transaction, need to acquire the EntityTransaction,
// start a transaction now and enlist a synchronization for commit or rollback later.
EntityTransaction et = this.target.getTransaction();
et.begin();
if (logger.isDebugEnabled()) {
logger.debug("Starting resource-local transaction on application-managed " +
"EntityManager [" + this.target + "]");
}
ExtendedEntityManagerSynchronization extendedEntityManagerSynchronization =
new ExtendedEntityManagerSynchronization(this.target, this.exceptionTranslator);
TransactionSynchronizationManager.bindResource(this.target, extendedEntityManagerSynchronization);
TransactionSynchronizationManager.registerSynchronization(extendedEntityManagerSynchronization);
}
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void testTransactionRollbackWithAlreadyRolledBack() {
given(manager.getTransaction()).willReturn(tx);
final List<String> l = new ArrayList<>();
l.add("test");
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
try {
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
assertTrue(TransactionSynchronizationManager.hasResource(factory));
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
throw new RuntimeException("some exception");
}
});
fail("Should have propagated RuntimeException");
}
catch (RuntimeException ex) {
// expected
}
assertTrue(!TransactionSynchronizationManager.hasResource(factory));
assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
verify(manager).close();
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected void doCommit(DefaultTransactionStatus status) {
JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
if (status.isDebug()) {
logger.debug("Committing JPA transaction on EntityManager [" +
txObject.getEntityManagerHolder().getEntityManager() + "]");
}
try {
EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
tx.commit();
}
catch (RollbackException ex) {
if (ex.getCause() instanceof RuntimeException) {
DataAccessException dae = getJpaDialect().translateExceptionIfPossible((RuntimeException) ex.getCause());
if (dae != null) {
throw dae;
}
}
throw new TransactionSystemException("Could not commit JPA transaction", ex);
}
catch (RuntimeException ex) {
// Assumably failed to flush changes to database.
throw DataAccessUtils.translateIfNecessary(ex, getJpaDialect());
}
}
代码示例来源:origin: hibernate/hibernate-orm
try {
entityManager = properties == null ?
factorySupplier.get().createEntityManager():
factorySupplier.get().createEntityManager(properties);
function.beforeTransactionCompletion();
txn = entityManager.getTransaction();
txn.begin();
function.accept( entityManager );
if ( !txn.getRollbackOnly() ) {
txn.commit();
function.afterTransactionCompletion();
if ( entityManager != null ) {
entityManager.close();
代码示例来源:origin: spring-projects/spring-framework
@Test
public void testTransactionCommitWithExtendedEntityManager() {
given(manager.getTransaction()).willReturn(tx);
tt.execute(status -> {
bean.extendedEntityManager.flush();
return null;
});
verify(tx, times(2)).commit();
verify(manager).flush();
verify(manager).close();
}
内容来源于网络,如有侵权,请联系作者删除!