下面列出了怎么用javax.persistence.EntityTransaction的API类实例代码及写法,或者点击链接到github查看源代码。
public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException {
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
Publisher publisher = em.find(Publisher.class, authorizedName);
if (publisher == null) {
throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
}
return publisher;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
private <R, T> R execute(final Function<T, R> function) {
final EntityTransaction tx = em.getTransaction();
final boolean wasActive = beforeTransactionBegin(tx);
try {
transactionBegin(tx);
final R ret = function.apply(null);
transactionCommit(tx);
if (flushOnCommit) {
em.flush();
}
if (clearOnCommit) {
em.clear();
}
return ret;
} finally {
afterTransactionCommit(tx, wasActive);
}
}
public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException, FatalErrorException {
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
Publisher publisher = em.find(Publisher.class, authorizedName);
if (publisher == null)
throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
return publisher;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException {
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
Publisher publisher = null;
try {
tx.begin();
publisher = em.find(Publisher.class, authorizedName);
if (publisher == null)
throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
AuthToken at = em.find(AuthToken.class, authInfo);
if (at == null)
throw new AuthTokenRequiredException(new ErrorMessage("E_authTokenRequired", authInfo));
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
return publisher;
}
@Test
public void testProductVersionBrewTagGeneration() {
EntityManager em = getEmFactory().createEntityManager();
EntityTransaction tx = em.getTransaction();
final String version = "10.1";
Product product = Product.Builder.newBuilder().id(1).build();
ProductVersion productVersionOriginal = ProductVersion.Builder.newBuilder()
.version(version)
.product(product)
.generateBrewTagPrefix("TP1", version, "${product_short_name}-${product_version}-pnc")
.build();
tx.begin();
em.persist(productVersionOriginal);
tx.commit();
ProductVersion productVersionLoaded = em.find(ProductVersion.class, productVersionOriginal.getId());
Assert.assertEquals(
"tp1-" + version + "-pnc",
productVersionLoaded.getAttributes().get(Attributes.BREW_TAG_PREFIX));
}
private static void endTransaction(EntityTransaction tx) {
if (tx != null && tx.isActive()) {
if (tx.getRollbackOnly()) {
tx.rollback();
} else {
try {
tx.commit();
} catch (RollbackException e) {
if (tx.isActive()) {
tx.rollback();
}
throw e;
}
}
}
}
@Test
public void testDelete() {
EntityManager em = null;
EntityTransaction tx = null;
try {
// 1、获取EntityManager
em = JpaUtil.getEntityManager();
// 2、获取事务
tx = em.getTransaction();
// 3、开启事务
tx.begin();
// 4、获取数据、删除数据
// primaryKey类型必须和实体主键类型一致,否则查询不到
Customer customer = em.find(Customer.class, 2L);
System.out.println(customer);
// 5、提交事务
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
} finally {
if (em != null) em.close();
}
}
private boolean rollbackTransaction() {
boolean ret = false;
EntityTransaction trx = null;
try {
trx = getTransaction();
if (trx != null && trx.isActive()) {
trx.rollback();
ret = true;
} else {
throw new Exception("trx is null or not active");
}
} catch (Throwable excp) {
logger.error("DBAuditDestination.rollbackTransaction(): failed",
excp);
cleanUp(); // so that next insert will try to init()
} finally {
clearEntityManager();
}
return ret;
}
/**
* Remove a mapping for the given user and domain
*/
private void doRemoveMapping(MappingSource source, String mapping) throws RecipientRewriteTableException {
EntityManager entityManager = entityManagerFactory.createEntityManager();
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
entityManager.createNamedQuery("deleteMapping")
.setParameter("user", source.getFixedUser())
.setParameter("domain", source.getFixedDomain())
.setParameter("targetAddress", mapping)
.executeUpdate();
transaction.commit();
} catch (PersistenceException e) {
LOGGER.debug("Failed to remove mapping", e);
if (transaction.isActive()) {
transaction.rollback();
}
throw new RecipientRewriteTableException("Unable to remove mapping", e);
} finally {
EntityManagerUtils.safelyClose(entityManager);
}
}
private boolean commitTransaction() {
boolean ret = false;
EntityTransaction trx = null;
try {
trx = getTransaction();
if(trx != null && trx.isActive()) {
trx.commit();
ret =true;
} else {
throw new Exception("trx is null or not active");
}
} catch(Exception excp) {
logDbError("DbAuditProvider.commitTransaction(): failed", excp);
cleanUp(); // so that next insert will try to init()
} finally {
clearEntityManager();
}
return ret;
}
/**
* @param customer The customer to be updated
*/
public static void update(Customer customer) {
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.merge(customer);
transaction.commit();
} catch (Exception e) {
System.out.println(e);
transaction.rollback();
} finally {
em.close();
}
}
/**
* Removes a user from the repository
*
* @param name
* the user to remove from the repository
*/
@Override
public void removeUser(Username name) throws UsersRepositoryException {
EntityManager entityManager = entityManagerFactory.createEntityManager();
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
if (entityManager.createNamedQuery("deleteUserByName").setParameter("name", name.asString()).executeUpdate() < 1) {
transaction.commit();
throw new UsersRepositoryException("User " + name.asString() + " does not exist");
} else {
transaction.commit();
}
} catch (PersistenceException e) {
LOGGER.debug("Failed to remove user", e);
if (transaction.isActive()) {
transaction.rollback();
}
throw new UsersRepositoryException("Failed to remove user " + name.asString(), e);
} finally {
EntityManagerUtils.safelyClose(entityManager);
}
}
private static void verifyJPANamedQuery(final EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
TypedQuery<Person> typedQuery = em.createNamedQuery(
"get_person_by_name", Person.class);
typedQuery.setParameter("name", "Quarkus");
final Person singleResult = typedQuery.getSingleResult();
if (!singleResult.getName().equals("Quarkus")) {
throw new RuntimeException("Wrong result from named JPA query");
}
transaction.commit();
em.close();
}
protected boolean persistInATransaction(Object... obj) {
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
for(Object o : obj) {
em.persist(o);
}
tx.commit();
} catch (Exception e) {
System.out.println("FAILED TRANSACTION: " + e.toString());
tx.rollback();
return false;
}
return true;
}
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.create(AppExtension.class, MockApp.class));
MockApp app = (MockApp) store.get(MockApp.class);
if (app.isInstalled("jweb.database")) {
AbstractModule module = app.module("jweb.database");
Database database = module.require(Database.class);
EntityManager em = database.em();
EntityTransaction transaction = em.getTransaction();
try {
logger.info("reset database");
transaction.begin();
em.createNativeQuery(HSQL_RESET_SQL).executeUpdate();
} catch (Exception e) {
logger.error("failed to reset database", e);
} finally {
transaction.commit();
em.close();
}
}
}
@AroundInvoke
public Object manageTransaction(InvocationContext ctx) throws Exception {
EntityTransaction transaction = em.getTransaction();
if (!transaction.isActive()) {
transaction.begin();
LOGGER.debug("Transaction started");
}
INTERCEPTOR_COUNTER++;
Object result = null;
try {
result = ctx.proceed();
} catch (Exception e) {
if (isFirstInterceptor()) {
markRollbackTransaction(e);
}
throw e;
} finally {
processTransaction();
}
return result;
}
public static void deleteEntity(Class<?> entityClass, Object entityKey) {
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
Object obj = em.find(entityClass, entityKey);
em.remove(obj);
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
/**
* Add mapping for given user and domain
*/
private void doAddMapping(MappingSource source, String mapping) throws RecipientRewriteTableException {
EntityManager entityManager = entityManagerFactory.createEntityManager();
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
JPARecipientRewrite jpaRecipientRewrite = new JPARecipientRewrite(source.getFixedUser(), Domain.of(source.getFixedDomain()), mapping);
entityManager.persist(jpaRecipientRewrite);
transaction.commit();
} catch (PersistenceException e) {
LOGGER.debug("Failed to save virtual user", e);
if (transaction.isActive()) {
transaction.rollback();
}
throw new RecipientRewriteTableException("Unable to add mapping", e);
} finally {
EntityManagerUtils.safelyClose(entityManager);
}
}
/**
* Inserts a Download object into the database
*
* @param download The download to be inserted
*/
public static void insert(Download download) {
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.persist(download);
transaction.commit();
} catch (Exception e) {
System.err.println(e);
transaction.rollback();
} finally {
em.close();
}
}
protected <T> T executeInTransaction(EntityManagerOperation<T> operation) {
EntityManager em = getEntityManager();
EntityTransaction transaction = null;
T value;
try {
transaction = beginIfNeeded(em);
value = operation.apply(em);
flushIfNeeded(em);
commitIfNeeded(em);
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
throw e;
} finally {
closeIfNeeded(em);
}
return value;
}
@BeforeEach
void setup() {
database = database();
database.addEntityClassName(TestEntity.class);
database.addEntityClassName(TestView.class);
database.start();
EntityManager em = database.em();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
TestEntity entity = new TestEntity();
entity.id = UUID.randomUUID().toString();
em.persist(entity);
} finally {
transaction.commit();
em.close();
}
}
private RestAPIVO persist(APIMessage msg) {
RestAPIVO vo = new RestAPIVO();
vo.setUuid(msg.getId());
vo.setApiMessageName(msg.getMessageName());
vo.setState(RestAPIState.Processing);
EntityManager mgr = getEntityManager();
EntityTransaction tran = mgr.getTransaction();
try {
tran.begin();
mgr.persist(vo);
mgr.flush();
mgr.refresh(vo);
tran.commit();
return vo;
} catch (Exception e) {
ExceptionDSL.exceptionSafe(tran::rollback);
throw new CloudRuntimeException(e);
} finally {
ExceptionDSL.exceptionSafe(mgr::close);
}
}
private static void verifyReadWriteCollection(final EntityManagerFactory emf, int expectedSize,
Map<String, Counts> counts) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Trainer t1 = em.find(Trainer.class, 1L);
final List<Pokemon> pokemons = t1.getPokemons();
if (pokemons.size() != expectedSize)
throw new RuntimeException("Incorrect family size: " + pokemons.size() + ", expected: " + expectedSize);
transaction.commit();
em.close();
assertRegionStats(counts, stats);
}
public void populateUserTable(EntityManager entityManager) {
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
createUser(entityManager, "Robina Kuh", "[email protected]");
createUser(entityManager, "Wayne Interessierts", "[email protected]");
createUser(entityManager, "John Doe", "[email protected]");
createUser(entityManager, "Jane Dull", "[email protected]");
List<String> names = Names.getNames();
for (String name:names) {
createUser(entityManager, name, name.replace(" ", ".")+"@example.com");
}
transaction.commit();
} catch (Exception e) {
transaction.rollback();
}
}
@Override
public void saveOwner(Owner owner) {
EntityTransaction transaction = Owner.beginTxn();
boolean successful = false;
try {
owner.persist();
successful = true;
} finally {
if (transaction != null) {
if (successful) {
transaction.commit();
} else {
transaction.rollback();
}
}
}
}
private static void testDeleteViaQuery(final EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.createNativeQuery("Delete from Person").executeUpdate();
transaction.commit();
em.close();
Statistics stats = getStatistics(emf);
em = emf.createEntityManager();
transaction = em.getTransaction();
transaction.begin();
if (em.find(Person.class, 1L) != null
|| em.find(Person.class, 2L) != null
|| em.find(Person.class, 3L) != null
|| em.find(Person.class, 4L) != null) {
throw new RuntimeException("Persons should have been deleted");
}
transaction.commit();
em.close();
assertRegionStats(new Counts(0, 0, 4, 0), Person.class.getName(), stats);
}
private static void rebalanceCpsForPokemons(final EntityManagerFactory emf, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Pokemon igeldo = em.find(Pokemon.class, 3);
igeldo.setCp(2707);
Pokemon godzilla = em.find(Pokemon.class, 248);
godzilla.setCp(3834);
Pokemon blissey = em.find(Pokemon.class, 242);
blissey.setCp(2757);
transaction.commit();
em.close();
assertRegionStats(expected, Pokemon.class.getName(), stats);
}
private static void storeTestPokemons(final EntityManagerFactory emf, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Pokemon igeldo = new Pokemon(3, "Venusaur", 2555);
em.persist(igeldo);
final Pokemon godzilla = new Pokemon(248, "Tyranitar", 3670);
em.persist(godzilla);
final Pokemon khaleesi = new Pokemon(242, "Blissey", 3219);
em.persist(khaleesi);
transaction.commit();
em.close();
assertRegionStats(expected, Pokemon.class.getName(), stats);
}
private static void verifyJPANamedQuery(final EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
TypedQuery<Person> typedQuery = em.createNamedQuery(
"get_person_by_name", Person.class);
typedQuery.setParameter("name", "Quarkus");
final Person singleResult = typedQuery.getSingleResult();
if (!singleResult.getName().equals("Quarkus")) {
throw new RuntimeException("Wrong result from named JPA query");
}
transaction.commit();
em.close();
}
void executeInATransaction(Consumer<EntityManager> toExecuteInATransaction) {
EntityManager entityManager = emf.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
toExecuteInATransaction.accept(entityManager);
transaction.commit();
}