Java Examples for javax.persistence.EntityTransaction

The following java examples will help you to understand the usage of javax.persistence.EntityTransaction. These source code samples are taken from different open source projects.

Example 1
Project: sandboxes-master  File: Embedded_Test.java View source code
private List<Demo> readWithHibernate() {
    EntityManager entityManager = connector.entityManagerForLocalHsqlDatabase();
    EntityTransaction transaction = null;
    try {
        transaction = entityManager.getTransaction();
        transaction.begin();
        TypedQuery<Demo> query = entityManager.createNamedQuery("Demo.findAll", Demo.class);
        List<Demo> demos = query.getResultList();
        transaction.commit();
        return demos;
    } catch (Exception ex) {
        if (null != transaction) {
            transaction.rollback();
        }
        StringWriter stringWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(stringWriter));
        Assert.fail(stringWriter.toString());
    }
    throw new UnreachableCodeException();
}
Example 2
Project: goos-code-examples-master  File: JPATransactor.java View source code
public void perform(UnitOfWork unitOfWork) throws Exception {
    final EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    try {
        unitOfWork.work();
        transaction.commit();
    } catch (PersistenceException e) {
        throw e;
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    }
}
Example 3
Project: curso-javaee-primefaces-master  File: TestePedido.java View source code
public static void main(String[] args) {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("PedidoPU");
    EntityManager manager = factory.createEntityManager();
    EntityTransaction trx = manager.getTransaction();
    trx.begin();
    Cliente cliente = manager.find(Cliente.class, 1L);
    Produto produto = manager.find(Produto.class, 1L);
    Usuario vendedor = manager.find(Usuario.class, 1L);
    EnderecoEntrega enderecoEntrega = new EnderecoEntrega();
    enderecoEntrega.setLogradouro("Rua dos Mercados");
    enderecoEntrega.setNumero("1000");
    enderecoEntrega.setCidade("Uberlândia");
    enderecoEntrega.setUf("MG");
    enderecoEntrega.setCep("38400-123");
    Pedido pedido = new Pedido();
    pedido.setCliente(cliente);
    pedido.setDataCriacao(new Date());
    pedido.setDataEntrega(new Date());
    pedido.setFormaPagamento(FormaPagamento.CARTAO_CREDITO);
    pedido.setObservacao("Aberto das 08 às 18h");
    pedido.setStatus(StatusPedido.ORCAMENTO);
    pedido.setValorDesconto(BigDecimal.ZERO);
    pedido.setValorFrete(BigDecimal.ZERO);
    pedido.setValorTotal(new BigDecimal(23.2));
    pedido.setVendedor(vendedor);
    pedido.setEnderecoEntrega(enderecoEntrega);
    ItemPedido item = new ItemPedido();
    item.setProduto(produto);
    item.setQuantidade(10);
    item.setValorUnitario(new BigDecimal(2.32));
    item.setPedido(pedido);
    pedido.getItens().add(item);
    manager.persist(pedido);
    trx.commit();
}
Example 4
Project: hibernate-demos-master  File: HikeTest.java View source code
@Test
public void testClearDatabase() {
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    Hike hike = new Hike("San Francisco", "Oakland");
    Trip trip = new Trip();
    trip.name = "Nappa Valley Unit Test";
    hike.recommendedTrip = trip;
    trip.availableHikes.add(hike);
    entityManager.persist(trip);
    entityManager.persist(hike);
    transaction.commit();
    entityManager.clear();
    transaction = entityManager.getTransaction();
    transaction.begin();
    List<?> all = entityManager.createQuery("from Hike").getResultList();
    for (Hike object : (List<Hike>) all) {
        object.recommendedTrip = null;
        entityManager.remove(object);
    }
    all = entityManager.createQuery("from Trip").getResultList();
    for (Object object : all) {
        entityManager.remove(object);
    }
    transaction.commit();
}
Example 5
Project: titanic-javaee7-master  File: TransactionInterceptor.java View source code
@AroundInvoke
public Object invoke(InvocationContext context) throws Exception {
    EntityTransaction trx = manager.getTransaction();
    boolean criador = false;
    try {
        if (!trx.isActive()) {
            trx.begin();
            trx.rollback();
            trx.begin();
            criador = true;
        }
        return context.proceed();
    } catch (Exception e) {
        if (trx != null && criador) {
            trx.rollback();
        }
        throw e;
    } finally {
        if (trx != null && trx.isActive() && criador) {
            trx.commit();
        }
    }
}
Example 6
Project: Trivial4b-master  File: UsuarioFinderImpl.java View source code
public List<Usuario> findAll() {
    EntityManager em = Jpa.createEntityManager();
    EntityTransaction trx = em.getTransaction();
    // Contexto persistencia abierto
    try {
        trx.begin();
        return Jpa.getManager().createNamedQuery("Usuario.findAll", Usuario.class).getResultList();
    } catch (PersistenceException e) {
        try {
            throw new IOException("Base de datos NO conectada.");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    return null;
}
Example 7
Project: capedwarf-blue-master  File: JPATestBase.java View source code
protected <T> T run(EMAction<T> action, final boolean useTx) throws Throwable {
    final EntityManager em = getEMF().createEntityManager();
    try {
        EntityTransaction tx = null;
        if (useTx)
            tx = em.getTransaction();
        try {
            if (useTx)
                tx.begin();
            return action.go(em);
        } catch (Throwable t) {
            if (useTx)
                tx.setRollbackOnly();
            throw t;
        } finally {
            if (useTx) {
                if (tx.getRollbackOnly())
                    tx.rollback();
                else
                    tx.commit();
            }
        }
    } finally {
        em.close();
    }
}
Example 8
Project: cdi-test-master  File: EclipselinkConnectionWrapper.java View source code
@Override
public boolean runWithConnection() throws SQLException {
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        Connection connection = (Connection) entityManager.unwrap(Connection.class);
        if (connection == null) {
            transaction.rollback();
            return false;
        } else {
            if (!cleaner.isUnsatisfied()) {
                cleaner.get().run(connection);
            }
            transaction.commit();
            return true;
        }
    } catch (RuntimeException re) {
        transaction.rollback();
        return false;
    }
}
Example 9
Project: corespring-master  File: CrearMovimientos.java View source code
public static void main(String[] args) {
    EntityManager manager = JpaUtil.getEntityManager();
    EntityTransaction trx = manager.getTransaction();
    trx.begin();
    Calendar fechaVencimiento1 = Calendar.getInstance();
    fechaVencimiento1.set(2014, 10, 1, 0, 0, 0);
    Calendar fechaVencimiento2 = Calendar.getInstance();
    fechaVencimiento2.set(2014, 12, 10, 0, 0, 0);
    Persona cliente = new Persona();
    cliente.setNombre("Inversiones Ochoa");
    Persona proveedor = new Persona();
    proveedor.setNombre("Frenosa");
    Movimiento movimiento1 = new Movimiento();
    movimiento1.setDescripcion("Venta de acero 3 pulg.");
    movimiento1.setPersona(cliente);
    movimiento1.setFechaVencimiento(fechaVencimiento1.getTime());
    movimiento1.setFechaPago(fechaVencimiento1.getTime());
    movimiento1.setValor(new BigDecimal(103_000));
    movimiento1.setTipo(TipoMovimiento.INGRESO);
    Movimiento movimiento2 = new Movimiento();
    movimiento2.setDescripcion("Liquido de freno.");
    movimiento2.setPersona(proveedor);
    movimiento2.setFechaVencimiento(fechaVencimiento2.getTime());
    movimiento2.setFechaPago(fechaVencimiento2.getTime());
    movimiento2.setValor(new BigDecimal(68_000));
    movimiento2.setTipo(TipoMovimiento.SALIDA);
    manager.persist(cliente);
    manager.persist(proveedor);
    manager.persist(movimiento1);
    manager.persist(movimiento2);
    trx.commit();
    manager.close();
}
Example 10
Project: e4GeminiJPA-master  File: SavePersonHandler2.java View source code
@Execute
public void execute(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell) {
    try {
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        Person person = new Person("John", "Smith");
        em.persist(person);
        tx.commit();
        MessageDialog.openInformation(shell, "Person persisted", "Persisted person in test2 database!");
    } catch (Exception e) {
        MessageDialog.openError(shell, "Error persisting Person", "Derby bundle is not installed \n " + e.getMessage());
    } finally {
        em.clear();
    }
}
Example 11
Project: goodstuff-example-master  File: EntityManagerProducer.java View source code
public void register(boolean requireNew) {
    if (emf == null) {
        emf = Persistence.createEntityManagerFactory("goodstuff");
    }
    if (threadEntityManagers.get() == null) {
        threadEntityManagers.set(new Stack<EntityManager>());
    }
    Stack<EntityManager> emStack = threadEntityManagers.get();
    if (emStack.isEmpty()) {
        emStack.push(emf.createEntityManager());
    } else {
        EntityManager em = emStack.peek();
        EntityTransaction tx = em.getTransaction();
        if (tx.isActive() && requireNew) {
            emStack.push(emf.createEntityManager());
        }
    }
}
Example 12
Project: Hibernate-Search-on-action-master  File: JpaItemActionTest.java View source code
@Override
public void postSetUp() throws Exception {
    FullTextEntityManager entityManager = Search.getFullTextEntityManager(factory.createEntityManager());
    EntityTransaction tx = null;
    try {
        tx = entityManager.getTransaction();
        tx.begin();
        //manual indexing solution OK for small amounts of data
        List results = entityManager.createQuery("select i from " + Item.class.getName() + " i").getResultList();
        for (Object entity : results) {
            //index each element
            entityManager.index(entity);
        }
        //commit the index changes
        tx.commit();
    } finally {
        entityManager.close();
    }
}
Example 13
Project: myequivalents-master  File: ProvenanceManagerTest.java View source code
@Test
public void testProvenanceManager() throws InterruptedException {
    // Here we get the specific factory, since we want newProvRegistryManager() 
    ProvDbManagerFactory mgrFact = Resources.getInstance().getMyEqManagerFactory();
    EntityManager em = mgrFact.getEntityManagerFactory().createEntityManager();
    ProvenanceRegisterEntryDAO provDao = new ProvenanceRegisterEntryDAO(em);
    ProvenanceRegisterEntry e = new ProvenanceRegisterEntry("foo.user", "foo.op", p("foo.entity", Arrays.asList("acc1", "acc2", "acc3")));
    ProvenanceRegisterEntry e1 = new ProvenanceRegisterEntry("foo.user1", "foo.op1", p("foo.entity", Arrays.asList("acc1", "acc2", "acc3")));
    EntityTransaction ts = em.getTransaction();
    ts.begin();
    provDao.create(e);
    provDao.create(e1);
    ts.commit();
    // Now invoke the manager commands
    //
    ProvRegistryManager regMgr = mgrFact.newProvRegistryManager(ProvDbServiceManagerTest.adminUser.getEmail(), ProvDbServiceManagerTest.testSecret);
    List<ProvenanceRegisterEntry> result = regMgr.find("foo.user%", null, new DateTime().minusDays(3).toDate(), null, null);
    assertEquals("find() doesn't work!", 2, result.size());
    assertTrue("e is not in the find() result!", result.contains(e));
    assertTrue("e1 is not in the find() result!", result.contains(e1));
    String resultStr = regMgr.findAs("xml", "foo.user%", "foo.op%", null, null, Arrays.asList(p("foo.entity", "acc%")));
    out.println("---- XML Result -----\n" + resultStr);
    assertTrue("Wrong XML result!", resultStr.contains("<entry operation=\"foo.op\""));
    assertTrue("Wrong XML result!", resultStr.contains("<parameter"));
    assertTrue("Wrong XML result!", resultStr.contains("value=\"acc2\""));
    assertTrue("Wrong XML result!", resultStr.contains("value-type=\"foo.entity\"/>"));
    assertTrue("Wrong XML result!", resultStr.contains("timestamp"));
    regMgr.purge(new DateTime().minusMinutes(1).toDate(), null);
    // flushes data for certain DBs (eg, H2)
    em.close();
    provDao = new ProvenanceRegisterEntryDAO(em = mgrFact.getEntityManagerFactory().createEntityManager());
    assertEquals("purge() didn't work!", 1, provDao.find("foo.user%", null, null).size());
}
Example 14
Project: needle4j-master  File: DBPersistenceUnitTest.java View source code
@Test
public void testDB_withPersistenceUnit() throws Exception {
    final Person person = new Person();
    final EntityManager entityManager = db.getEntityManager();
    person.setMyName("My Name");
    assertNotNull(db);
    assertNotNull(entityManager);
    final EntityTransaction tx = entityManager.getTransaction();
    tx.begin();
    entityManager.persist(person);
    final Person fromDB = entityManager.find(Person.class, person.getId());
    assertSame(person, fromDB);
    tx.commit();
}
Example 15
Project: ping-service-master  File: RunJobFilter.java View source code
@Override
protected void processRequest(EntityTransaction tx) throws Exception {
    String encodedJobKey = globals.getHTTPServletRequest().getParameter(RunJobFilter.JOB_KEY_PARAMETER_NAME);
    if (Utils.isNullOrEmpty(encodedJobKey)) {
        return;
    }
    Key key = stringToKey(encodedJobKey);
    logger.debug("Running job: {}", key);
    Job job = jobDAO.find(key);
    if (job == null) {
        return;
    }
    if (job.isSuspended()) {
        logger.debug("{} suspended", job);
        return;
    }
    application.runJob(job);
    application.updateJob(job, false, true);
}
Example 16
Project: study-ocbcd-master  File: RelationshipOneToManyServlet.java View source code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    EntityManager em = ResourceFactory.getEM();
    String result = null;
    PersonOneToMany p = new PersonOneToMany();
    p.setName("Odair");
    p.addDog(new Dog("Bob", "Pitbull"));
    p.addDog(new Dog("Jason", "Rottweiler"));
    // get transation
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        em.persist(p);
        // foreach is not need because the relationship uses cascade
        //for(Cat dog : p.getDogs()) {
        //	em.persist(dog);
        //}
        em.flush();
        tx.commit();
        result = "Saved with successfully!";
    } catch (Exception ex) {
        result = ex.getMessage();
        ex.printStackTrace();
        tx.rollback();
    } finally {
        em.close();
    }
    response.getWriter().print("<html><body><h4>" + result + "</h4></body></html>");
}
Example 17
Project: jboss-seam-2.3.0.Final-Hibernate.3-master  File: EntityTransaction.java View source code
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    log.debug("committing JPA resource-local transaction");
    assertActive();
    javax.persistence.EntityTransaction delegate = getDelegate();
    clearEntityManager();
    boolean success = false;
    try {
        if (delegate.getRollbackOnly()) {
            delegate.rollback();
            throw new RollbackException();
        } else {
            getSynchronizations().beforeTransactionCommit();
            delegate.commit();
            success = true;
        }
    } finally {
        getSynchronizations().afterTransactionCommit(success);
    }
}
Example 18
Project: seam-2.2-master  File: EntityTransaction.java View source code
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    log.debug("committing JPA resource-local transaction");
    assertActive();
    javax.persistence.EntityTransaction delegate = getDelegate();
    clearEntityManager();
    boolean success = false;
    try {
        if (delegate.getRollbackOnly()) {
            delegate.rollback();
            throw new RollbackException();
        } else {
            getSynchronizations().beforeTransactionCommit();
            delegate.commit();
            success = true;
        }
    } finally {
        getSynchronizations().afterTransactionCommit(success);
    }
}
Example 19
Project: seam-revisited-master  File: EntityTransaction.java View source code
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    log.debug("committing JPA resource-local transaction");
    assertActive();
    javax.persistence.EntityTransaction delegate = getDelegate();
    clearEntityManager();
    boolean success = false;
    try {
        if (delegate.getRollbackOnly()) {
            delegate.rollback();
            throw new RollbackException();
        } else {
            getSynchronizations().beforeTransactionCommit();
            delegate.commit();
            success = true;
        }
    } finally {
        getSynchronizations().afterTransactionCommit(success);
    }
}
Example 20
Project: seam2jsf2-master  File: EntityTransaction.java View source code
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    log.debug("committing JPA resource-local transaction");
    assertActive();
    javax.persistence.EntityTransaction delegate = getDelegate();
    clearEntityManager();
    boolean success = false;
    try {
        if (delegate.getRollbackOnly()) {
            delegate.rollback();
            throw new RollbackException();
        } else {
            getSynchronizations().beforeTransactionCommit();
            delegate.commit();
            success = true;
        }
    } finally {
        getSynchronizations().afterTransactionCommit(success);
    }
}
Example 21
Project: taylor-seam-jsf2-master  File: EntityTransaction.java View source code
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    log.debug("committing JPA resource-local transaction");
    assertActive();
    javax.persistence.EntityTransaction delegate = getDelegate();
    clearEntityManager();
    boolean success = false;
    try {
        if (delegate.getRollbackOnly()) {
            delegate.rollback();
            throw new RollbackException();
        } else {
            getSynchronizations().beforeTransactionCommit();
            delegate.commit();
            success = true;
        }
    } finally {
        getSynchronizations().afterTransactionCommit(success);
    }
}
Example 22
Project: blaze-persistence-master  File: AbstractPersistenceTest.java View source code
@Override
protected Connection getConnection(EntityManager em) {
    EntityTransaction tx = em.getTransaction();
    boolean startedTransaction = !tx.isActive();
    try {
        if (startedTransaction) {
            tx.begin();
        }
        return em.unwrap(Connection.class);
    } finally {
        if (startedTransaction) {
            tx.commit();
        }
    }
}
Example 23
Project: civilian-master  File: JpaContext.java View source code
public static void closeEm(boolean commit) {
    EntityManager em = EM_THREADLOCAL.get();
    if (em != null) {
        EM_THREADLOCAL.remove();
        try {
            EntityTransaction txn = em.getTransaction();
            if (txn.isActive()) {
                if (commit)
                    txn.commit();
                else
                    txn.rollback();
            }
        } finally {
            em.close();
        }
    }
}
Example 24
Project: compass-fork-master  File: EmbeddedToplinkSimpleJpaGpsDeviceTests.java View source code
public void testRollbackTransaction() throws Exception {
    compassGps.index();
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();
    // insert a new one
    Simple simple = new Simple();
    simple.setId(4);
    simple.setValue("value4");
    entityManager.persist(simple);
    entityManager.flush();
    CompassSession compassSession = TopLinkHelper.getCurrentCompassSession(entityManager);
    simple = compassSession.get(Simple.class, 4);
    assertNotNull(simple);
    CompassSession otherCompassSession = TopLinkHelper.getCurrentCompassSession(entityManager);
    assertSame(compassSession, otherCompassSession);
    entityTransaction.rollback();
    entityManager.close();
    CompassSession sess = compass.openSession();
    CompassTransaction tr = sess.beginTransaction();
    simple = sess.get(Simple.class, 4);
    assertNull(simple);
    tr.commit();
    sess.close();
}
Example 25
Project: debop4j-master  File: JPAResourceLocalStandaloneTest.java View source code
@Test
public void jtaStandalone() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpajtastandalone");
    try {
        final EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            Poem poem = new Poem();
            poem.setName("L'albatros");
            em.persist(poem);
            em.getTransaction().commit();
            em.clear();
            em.getTransaction().begin();
            Poem poem2 = new Poem();
            poem2.setName("Mazaaaa");
            em.persist(poem2);
            em.flush();
            assertThat(TestHelper.assertNumberOfEntities(2, em)).isTrue();
            em.getTransaction().rollback();
            assertThat(TestHelper.assertNumberOfEntities(1, em)).isTrue();
            em.getTransaction().begin();
            poem = em.find(Poem.class, poem.getId());
            assertThat(poem).isNotNull();
            assertThat(poem.getName()).isEqualTo("L'albatros");
            em.remove(poem);
            poem2 = em.find(Poem.class, poem2.getId());
            assertThat(poem2).isNull();
            em.getTransaction().commit();
        } finally {
            EntityTransaction transaction = em.getTransaction();
            if (transaction != null && transaction.isActive()) {
                transaction.rollback();
            }
            em.close();
        }
    } finally {
        TestHelper.dropSchemaAndDatabase(emf);
        emf.close();
    }
}
Example 26
Project: dragome-examples-master  File: EntitiesProviderServiceImpl.java View source code
private void createPeople() {
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    entityManager.persist(new People("Diego Maradona", new Place("Villa Fiorito, Buenos Aires, Argentina")));
    entityManager.persist(new People("Ariel Ortega", new Place("Ledesma, Jujuy, Argentina")));
    entityManager.persist(new People("Ricardo Bochini", new Place("Zárate, Buenos Aires, Argentina")));
    transaction.commit();
}
Example 27
Project: exsite9-master  File: MetadataCategoryDAOUnitTest.java View source code
@Test
public void testCreateMetadataCategory() {
    final EntityManager em = Mockito.mock(EntityManager.class);
    final EntityTransaction et = Mockito.mock(EntityTransaction.class);
    final MetadataCategoryDAO toTest = new MetadataCategoryDAO(em);
    final MetadataCategory mdc = new MetadataCategory("My MDC Name", MetadataCategoryType.CONTROLLED_VOCABULARY, MetadataCategoryUse.optional);
    when(em.getTransaction()).thenReturn(et);
    toTest.createMetadataCategory(mdc);
    verify(et).begin();
    verify(em).persist(mdc);
    verify(et).commit();
}
Example 28
Project: graniteds-master  File: TestHibernate4Externalizer.java View source code
@Test
public void testSerializationProxy3() throws Exception {
    GraniteContext gc = SimpleGraniteContext.createThreadInstance(graniteConfig, servicesConfig, new HashMap<String, Object>());
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction et = entityManager.getTransaction();
    et.begin();
    Entity8 e8 = new Entity8();
    e8.setName("Test");
    Entity7 e7 = new Entity7();
    e7.setName("Test");
    e7.setEntity8(e8);
    entityManager.persist(e7);
    entityManager.flush();
    et.commit();
    entityManager.close();
    entityManager = entityManagerFactory.createEntityManager();
    et = entityManager.getTransaction();
    et.begin();
    e7 = entityManager.find(Entity7.class, e7.getId());
    entityManager.flush();
    et.commit();
    entityManager.close();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(20000);
    ObjectOutput out = ((AMF3Config) gc.getGraniteConfig()).newAMF3Serializer(baos);
    out.writeObject(e7);
    out.close();
    GraniteContext.release();
    InputStream is = new ByteArrayInputStream(baos.toByteArray());
    gc = SimpleGraniteContext.createThreadInstance(graniteConfig, servicesConfig, new HashMap<String, Object>());
    ObjectInput in = ((AMF3Config) gc.getGraniteConfig()).newAMF3Deserializer(is);
    Object obj = in.readObject();
    in.close();
    GraniteContext.release();
    Assert.assertTrue("Entity7", obj instanceof Entity7);
    e7 = (Entity7) obj;
    Long e8id = e7.getEntity8().getId();
    Assert.assertEquals("Entity8 id", e8.getId(), e8id);
}
Example 29
Project: hibernate-orm-master  File: CascadeWithFkConstraintTestTask.java View source code
public void prepare() {
    Configuration cfg = new Configuration();
    cfg.setProperty(Environment.ENABLE_LAZY_LOAD_NO_TRANS, "true");
    cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "false");
    super.prepare(cfg);
    // Create garage, add 2 cars to garage
    EntityManager em = getFactory().createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    Garage garage = new Garage();
    Car car1 = new Car();
    Car car2 = new Car();
    garage.insert(car1);
    garage.insert(car2);
    em.persist(garage);
    em.persist(car1);
    em.persist(car2);
    tx.commit();
    em.close();
    garageId = garage.id;
    car1Id = car1.id;
    car2Id = car2.id;
}
Example 30
Project: jstryker-master  File: JPAHelperTest.java View source code
@Test
public void shouldRollbackTransactionOnClose() throws Exception {
    EntityTransaction transaction = mock(EntityTransaction.class);
    EntityManager entityManager = mock(EntityManager.class);
    when(entityManager.getTransaction()).thenReturn(transaction);
    ReflectionHelper.injectValueInStaticField(JPAHelper.class, "entityManager", entityManager);
    JPAHelper.close();
    verify(transaction).rollback();
}
Example 31
Project: keycloak-master  File: TransactionInterceptor.java View source code
@AroundInvoke
public Object aroundInvoke(InvocationContext context) {
    EntityManager entityManager = this.entityManager.get();
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        Object proceed = context.proceed();
        transaction.commit();
        return proceed;
    } catch (Exception cause) {
        if (transaction != null && transaction.isActive()) {
            transaction.rollback();
        }
        throw new RuntimeException(cause);
    } finally {
        entityManager.close();
    }
}
Example 32
Project: lavoi-master  File: GenericDAO.java View source code
public Serializable insert(Serializable entity) {
    EntityManager entityManager = createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    if (!transaction.isActive()) {
        transaction.begin();
    }
    try {
        entityManager.persist(entity);
        transaction.commit();
        return entity;
    } catch (RollbackException rE) {
        throw rE;
    } catch (Exception e) {
        transaction.rollback();
        throw new RuntimeException(e);
    }
}
Example 33
Project: lunifera-dsl-master  File: ModelTestcarstore3Tests.java View source code
@Before
public void setUp() throws Exception {
    super.setUp();
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
    EntityManager em = emf.createEntityManager();
    EntityTransaction txn = em.getTransaction();
    txn.begin();
    Car c = em.find(Car.class, 2L);
    assertNull(c);
    try {
        Query q = em.createNativeQuery("create schema SCHEMA3");
        q.executeUpdate();
        txn.commit();
    } catch (Exception e) {
        txn.rollback();
    }
    txn = em.getTransaction();
    Manufacturer manufacturer = new Manufacturer();
    Car car = new Car();
    manufacturer.setName("Lunifera Racecars");
    car.setConstructiondate(new Date(2012, 4, 4));
    car.setModelname("Beta Romeo");
    car.setManufacturer(manufacturer);
    txn.begin();
    em.persist(manufacturer);
    txn.commit();
}
Example 34
Project: motown-master  File: SubscriptionRepository.java View source code
private void executeWithinTransaction(TransactionalTask task, EntityManager entityManager) {
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        if (!transaction.isActive()) {
            transaction.begin();
        }
        task.execute();
        transaction.commit();
    } finally {
        if (transaction.isActive()) {
            LOG.warn("Transaction is still active while it should not be, rolling back.");
            transaction.rollback();
        }
    }
}
Example 35
Project: openjpa-master  File: TestPersistence.java View source code
public void testCreateEntityManager() {
    OpenJPAEntityManagerFactorySPI emf = createNamedEMF("xmlstore-simple");
    try {
        EntityManager em = emf.createEntityManager();
        EntityTransaction t = em.getTransaction();
        assertNotNull(t);
        t.begin();
        t.setRollbackOnly();
        t.rollback();
        // openjpa-facade test
        assertTrue(em instanceof OpenJPAEntityManager);
        OpenJPAEntityManager ojem = (OpenJPAEntityManager) em;
        ojem.getFetchPlan().setMaxFetchDepth(1);
        assertEquals(1, ojem.getFetchPlan().getMaxFetchDepth());
        em.close();
    } finally {
        closeEMF(emf);
    }
}
Example 36
Project: PFRPG-Toolset-master  File: EntityManagerUtil.java View source code
public static List<?> query(String namedQuery) {
    LOG.debug("Running query: " + namedQuery);
    List<?> list = new LinkedList<Object>();
    EntityTransaction tx = entityManager.getTransaction();
    tx.begin();
    list = entityManager.createNamedQuery(namedQuery).getResultList();
    tx.commit();
    LOG.debug("Query result count: " + list.size());
    return list;
}
Example 37
Project: Practical-Apache-Struts-2-Web-2.0-Projects-master  File: VotingServiceImpl.java View source code
public void enroll(User user, Long eventId) {
    EntityManager entityMgr = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        tx = entityMgr.getTransaction();
        tx.begin();
        Event event = entityMgr.find(Event.class, eventId);
        Voter voter = new Voter();
        Calendar cal = Calendar.getInstance();
        voter.setEnrollmentTime(cal.getTime());
        voter.setEvent(event);
        voter.setUser(user);
        entityMgr.persist(voter);
        event.addVoter(voter);
        entityMgr.persist(event);
        tx.commit();
    } catch (Exception e) {
        if (tx != null && tx.isActive())
            tx.rollback();
        throw (RuntimeException) e.getCause();
    }
}
Example 38
Project: Processiva-master  File: ProcessInstanceInfoDao.java View source code
@Transactional
public List<ProcessInstanceInfo> getRunningInstances(String processId) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    Query query = em.createNativeQuery("Select * from processinstanceinfo where processid = '" + processId + "'", ProcessInstanceInfo.class);
    List<ProcessInstanceInfo> list = query.getResultList();
    tx.commit();
    return list;
}
Example 39
Project: PSN-API-master  File: AdminServiceImpl.java View source code
/**
   * dump the data.
   */
@Override
public int savepoint() {
    int ec = ExitCode.NORMAL.getCode();
    // save cookies
    try {
        SystemSetting.INSTANCE.persist();
    } catch (IOException e1) {
        ec &= ExitCode.COOKIE_SAVE_FAILED.getCode();
    }
    // dump db
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        adminDao.dumpData();
        tx.commit();
    } catch (Exception e) {
        logger.error("failed to dump data. Cause: " + ExceptionUtil.getFullStackTrace(e));
        tx.rollback();
        ec &= ExitCode.DB_DUMP_FAILED.getCode();
    }
    return ec;
}
Example 40
Project: raidenjpa-master  File: MergeTest.java View source code
@Test
public void testSimpleTx() {
    A a = new A("a1", 1);
    B b = new B("b");
    C c = new C("c");
    EntityManager em = EntityManagerUtil.em();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    a = em.merge(a);
    b = em.merge(b);
    c = em.merge(c);
    a.setB(b);
    b.setC(c);
    tx.commit();
    em.close();
    em = EntityManagerUtil.em();
    a = em.find(A.class, a.getId());
    assertEquals(a.getStringValue(), "a1");
    assertEquals(a.getB().getValue(), "b");
    assertEquals(a.getB().getC().getValue(), "c");
    em.close();
}
Example 41
Project: skalli-master  File: JPAFeedPersistenceComponent.java View source code
@Override
public void merge(Collection<FeedEntry> entries) throws IOException {
    for (FeedEntry entry : entries) {
        EntityManager em = getEntityManager();
        EntityTransaction tx = null;
        try {
            tx = em.getTransaction();
            tx.begin();
            em.merge(entry);
            tx.commit();
        } catch (Exception e) {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
            throw new IOException(MessageFormat.format("Failed to persist {0} ({1})", EntryJPA.class.getSimpleName(), entry.getProjectId().toString()), e);
        } finally {
            em.close();
        }
    }
}
Example 42
Project: SlipStreamServer-master  File: VmTest.java View source code
@Test
public void cloudInstanceIdUserMustBeUnique() throws Exception {
    boolean exceptionOccured = false;
    boolean firstInsertAccepted = false;
    EntityManager em = PersistenceUtil.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        String sqlInsert1 = String.format("INSERT INTO Vm (ID, CLOUD, INSTANCEID, STATE, USER_) VALUES (10, 'lokal', 'instance100', 'up', '%s');", user.getName());
        String sqlInsert2 = String.format("INSERT INTO Vm (ID, CLOUD, INSTANCEID, STATE, USER_) VALUES (10, 'lokal', 'instance100', 'down', '%s');", user.getName());
        Query query1 = em.createNativeQuery(sqlInsert1);
        Query query2 = em.createNativeQuery(sqlInsert2);
        int res = query1.executeUpdate();
        assertEquals(1, res);
        firstInsertAccepted = true;
        res = query2.executeUpdate();
        transaction.commit();
    } catch (PersistenceException pe) {
        exceptionOccured = true;
        transaction.rollback();
        boolean isCorrectException = pe.getCause().getCause().getClass() == SQLIntegrityConstraintViolationException.class;
        assertTrue("The cause of the cause sould be SQLIntegrityConstraintViolationException.", isCorrectException);
    }
    assertTrue("First insert should have worked", firstInsertAccepted);
    assertTrue("Second insert should have failed", exceptionOccured);
}
Example 43
Project: spring-data-graph-examples-master  File: AbstractTestWithUserAccount.java View source code
@BeforeTransaction
public void setUpBeforeTransaction() {
    EntityManager setUpEm = emf.createEntityManager();
    EntityTransaction setUpTx = setUpEm.getTransaction();
    setUpTx.begin();
    UserAccount u = new UserAccount();
    u.setFirstName("Bubba");
    u.setLastName("Jones");
    u.setBirthDate(new Date());
    u.setUserName("user");
    setUpEm.persist(u);
    setUpEm.flush();
    u.persist();
    this.userId = u.getId();
    setUpTx.commit();
}
Example 44
Project: spring-framework-2.5.x-master  File: DefaultJpaDialectTests.java View source code
public void testDefaultBeginTransaction() throws Exception {
    TransactionDefinition definition = new DefaultTransactionDefinition();
    MockControl entityControl = MockControl.createControl(EntityManager.class);
    EntityManager entityManager = (EntityManager) entityControl.getMock();
    MockControl txControl = MockControl.createControl(EntityTransaction.class);
    EntityTransaction entityTx = (EntityTransaction) txControl.getMock();
    entityControl.expectAndReturn(entityManager.getTransaction(), entityTx);
    entityTx.begin();
    entityControl.replay();
    txControl.replay();
    dialect.beginTransaction(entityManager, definition);
    entityControl.verify();
    txControl.verify();
}
Example 45
Project: spring-framework-master  File: DefaultJpaDialectTests.java View source code
@Test
public void testDefaultBeginTransaction() throws Exception {
    TransactionDefinition definition = new DefaultTransactionDefinition();
    EntityManager entityManager = mock(EntityManager.class);
    EntityTransaction entityTx = mock(EntityTransaction.class);
    given(entityManager.getTransaction()).willReturn(entityTx);
    dialect.beginTransaction(entityManager, definition);
}
Example 46
Project: sujet-2-master  File: Facade.java View source code
public void persist(VO vo) throws DatabaseException {
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();
        service.persist(vo, em);
        tx.commit();
    } catch (Exception e) {
        if (em != null && tx != null) {
            tx.rollback();
        }
        throw new PersistException(e.getMessage());
    } finally {
        if (em != null) {
            em.clear();
            em.close();
        }
    }
}
Example 47
Project: turmeric-releng-master  File: EntityManagerContext.java View source code
public static void close() {
    boolean close = reentrancy.get().decrementAndGet() == 0;
    if (close) {
        EntityManager entityManager = get();
        EntityManagerContext.entityManager.set(null);
        EntityTransaction transaction = entityManager.getTransaction();
        if (transaction != null) {
            if (transaction.getRollbackOnly()) {
                rollback(transaction);
            } else {
                try {
                    transaction.commit();
                } catch (RuntimeException x) {
                    rollback(transaction);
                }
            }
        }
    }
}
Example 48
Project: two-freestyle-master  File: BrowseDataServlet.java View source code
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    EntityManager em = null;
    EntityTransaction tx = null;
    Writer writer = null;
    try {
        EntityManagerFactory emf = (EntityManagerFactory) getServletContext().getAttribute("emf");
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        final Query q = em.createQuery("from LoggedRequest");
        final List<LoggedRequest> result = q.getResultList();
        tx.commit();
        resp.setHeader("Content-type", "text/html; charset=utf-8");
        writer = new OutputStreamWriter(resp.getOutputStream(), "utf-8");
        writer.write("<html><head>" + "<meta http-equiv=\"content-type\" content=\"utf-8\">" + "<meta name=\"robots\" content=\"none\">" + "</head><body>");
        writer.write("<table>");
        for (LoggedRequest loggedRequest : result) {
            writer.write("<tr><td>" + loggedRequest.getAgent() + "</td><td>" + loggedRequest.getPath() + "</td><td>" + loggedRequest.getDate() + "</tr>");
        }
        writer.write("</table>");
        writer.write("</body></html>");
    } catch (Exception e) {
        logger.error(e);
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}
Example 49
Project: webpie-master  File: PopulateDatabase.java View source code
private void createSomeData() {
    EntityManager mgr = factory.createEntityManager();
    List<UserDbo> users = UserDbo.findAll(mgr);
    if (users.size() > 0)
        //This database has users, exit immediately to not screw up existing data 
        return;
    EntityTransaction tx = mgr.getTransaction();
    tx.begin();
    UserDbo user1 = new UserDbo();
    user1.setEmail("dean@somewhere.com");
    user1.setName("SomeName");
    user1.setFirstName("Dean");
    user1.setLastName("Hill");
    UserDbo user2 = new UserDbo();
    user2.setEmail("bob@somewhere.com");
    user2.setName("Bob'sName");
    user2.setFirstName("Bob");
    user2.setLastName("LastBob");
    user2.setLevelOfEducation(EducationEnum.MIDDLE_SCHOOL);
    UserRole role1 = new UserRole(user2, RoleEnum.DELINQUINT);
    UserRole role2 = new UserRole(user2, RoleEnum.BADASS);
    mgr.persist(user1);
    mgr.persist(user2);
    mgr.persist(role1);
    mgr.persist(role2);
    mgr.flush();
    tx.commit();
}
Example 50
Project: activityinfo-master  File: TransactionalInterceptorTest.java View source code
@Test
public void testSuccessfulCase() {
    EntityTransaction tx = createMock(EntityTransaction.class);
    expect(tx.isActive()).andReturn(false);
    tx.begin();
    expect(tx.isActive()).andReturn(true);
    tx.commit();
    replay(tx);
    MockClass mock = getMockInstance(tx);
    mock.succeedsWithoutException();
    verify(tx);
}
Example 51
Project: anudc-master  File: UsersTest.java View source code
/**
	 * test
	 * 
	 * Performs a test on the users ant user_registered tables
	 * 
	 * <pre>
	 * Version	Date		Developer				Description
	 * 0.1		17/05/2012	Genevieve Turner (GT)	Initial
	 * </pre>
	 */
@Test
public void test() {
    UserRegistered user_registered = new UserRegistered();
    user_registered.setGiven_name("test");
    user_registered.setLast_name("user");
    Users user = new Users();
    user.setUsername("testuser1");
    user.setPassword("testpassword1");
    user.setEnabled(Boolean.TRUE);
    user.setUser_type(new Long(2));
    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();
    entityManager.persist(user);
    entityTransaction.commit();
    user_registered.setUser(user);
    user_registered.setId(user.getId());
    user.setUser_registered(user_registered);
    entityTransaction.begin();
    entityManager.persist(user);
    entityTransaction.commit();
    LOGGER.info("After committing registered user");
    List<Users> users = entityManager.createQuery("from Users where username='testuser1'", Users.class).getResultList();
    for (Users savedUser : users) {
        assertEquals("testuser1", savedUser.getUsername());
        assertEquals("testpassword1", savedUser.getPassword());
        assertEquals(Boolean.TRUE, savedUser.getEnabled());
        assertEquals(new Long(2), savedUser.getUser_type());
        assertEquals("test", savedUser.getUser_registered().getGiven_name());
        assertEquals("user", savedUser.getUser_registered().getLast_name());
        entityTransaction.begin();
        entityManager.remove(savedUser);
        entityTransaction.commit();
    }
}
Example 52
Project: beanlet-master  File: ThreadLocalEntityManager.java View source code
@Override
void postInvoke(boolean commit) {
    if (ixLocal.get().decrementAndGet() == 0) {
        EntityManager em = getEntityManager();
        try {
            EntityTransaction tx = em.getTransaction();
            if (!commit || tx.getRollbackOnly()) {
                tx.rollback();
            } else {
                tx.commit();
            }
        } finally {
            emLocal.remove();
            em.close();
        }
    }
}
Example 53
Project: btpka3.github.com-master  File: JpaTest.java View source code
public static void add(EntityManagerFactory emf, int count) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction entityTransaction = em.getTransaction();
    entityTransaction.begin();
    for (int i = 0; i < count; i++) {
        User user = new User();
        user.setName("z-" + Math.abs(random.nextLong()));
        em.persist(user);
    }
    entityTransaction.commit();
    em.close();
    System.out.println("Added.");
}
Example 54
Project: capedwarf-green-master  File: Work.java View source code
public final T workInTransaction(EntityTransaction transaction) throws Exception {
    boolean newTransactionRequired = isNewTransactionRequired(transaction.isActive());
    EntityTransaction userTransaction = newTransactionRequired ? transaction : null;
    if (newTransactionRequired) {
        userTransaction.begin();
    }
    try {
        T result = work();
        if (newTransactionRequired) {
            if (transaction.getRollbackOnly()) {
                userTransaction.rollback();
            } else {
                userTransaction.commit();
            }
        }
        return result;
    } catch (Exception e) {
        T fallback = handleException(e);
        if (newTransactionRequired && fallback == null && userTransaction.isActive()) {
            try {
                userTransaction.rollback();
            } catch (Exception ignored) {
            }
        }
        if (fallback == null)
            throw e;
        return fallback;
    }
}
Example 55
Project: clinic-softacad-master  File: DeleteOrphanTest.java View source code
@Test
public void testDeleteOrphan() throws Exception {
    EntityTransaction tx;
    EntityManager em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    Troop disney = new Troop();
    disney.setName("Disney");
    Soldier mickey = new Soldier();
    mickey.setName("Mickey");
    disney.addSoldier(mickey);
    em.persist(disney);
    tx.commit();
    em.close();
    em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    Troop troop = em.find(Troop.class, disney.getId());
    Hibernate.initialize(troop.getSoldiers());
    tx.commit();
    em.close();
    Soldier soldier = troop.getSoldiers().iterator().next();
    troop.getSoldiers().remove(soldier);
    troop = (Troop) deserialize(serialize(troop));
    em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    em.merge(troop);
    tx.commit();
    em.close();
    em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    soldier = em.find(Soldier.class, mickey.getId());
    Assert.assertNull("delete-orphan should work", soldier);
    troop = em.find(Troop.class, disney.getId());
    em.remove(troop);
    tx.commit();
    em.close();
}
Example 56
Project: cmestemp22-master  File: InsertBulkMapperTest.java View source code
/**
     * Test execute method.
     */
@SuppressWarnings("unchecked")
@Test
public void testExecute() {
    final EntityManager entityManager = context.mock(EntityManager.class);
    final PersistenceListRequest req = context.mock(PersistenceListRequest.class);
    final Session session = context.mock(Session.class);
    final EntityTransaction transaction = context.mock(EntityTransaction.class);
    final List<Activity> activities = new LinkedList<Activity>();
    for (int i = 0; i < NUMOFACTIVITY; i++) {
        activities.add(context.mock(Activity.class, "a" + String.valueOf(i)));
    }
    InsertBulkMapper sut = new InsertBulkMapper();
    sut.setEntityManager(entityManager);
    context.checking(new Expectations() {

        {
            oneOf(req).getDomainEnities();
            will(returnValue(activities));
            oneOf(entityManager).getDelegate();
            will(returnValue(session));
            exactly(NUMOFACTIVITY).of(session).save(with(any(Activity.class)));
            exactly(5).of(session).flush();
            exactly(5).of(session).clear();
            oneOf(entityManager).getTransaction();
            will(returnValue(transaction));
            oneOf(transaction).commit();
            oneOf(session).close();
        }
    });
    assertTrue(sut.execute(req));
    context.assertIsSatisfied();
}
Example 57
Project: coherence-tools-master  File: JpaTarget.java View source code
// ---- helper methods --------------------------------------------------
/**
     * Persist collection of objects.
     *
     * @param em      entity manager used to persist objects
     * @param objects objects to persist
     */
private void mergeInTransaction(EntityManager em, Collection objects) {
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();
        for (Object o : objects) {
            em.merge(o);
        }
        tx.commit();
    } catch (RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    }
}
Example 58
Project: ComplexEventProcessingPlatform-master  File: QueryMonitoringPoint.java View source code
/**
	 * Deletes all query monitoring points from the database.
	 */
public static void removeAll() {
    try {
        EntityTransaction entr = Persistor.getEntityManager().getTransaction();
        entr.begin();
        Query query = Persistor.getEntityManager().createQuery("DELETE FROM QueryMonitoringPoint");
        int deleteRecords = query.executeUpdate();
        entr.commit();
        System.out.println(deleteRecords + " records are deleted.");
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}
Example 59
Project: dwoss-master  File: StockTransactionEaoIT.java View source code
@Test
public void testfind() {
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    Stock s1 = new Stock(0, "TEEEEEEEST");
    Stock s2 = new Stock(1, "TEEEEEEEST");
    em.persist(s1);
    em.persist(s2);
    StockTransaction st1 = new StockTransaction(StockTransactionType.ROLL_IN);
    st1.setDestination(s1);
    st1.addStatus(new StockTransactionStatus(StockTransactionStatusType.PREPARED, new Date()));
    st1.addStatus(new StockTransactionStatus(StockTransactionStatusType.COMPLETED, new Date()));
    StockTransaction st2 = new StockTransaction(StockTransactionType.ROLL_IN);
    st2.setDestination(s1);
    st2.addStatus(new StockTransactionStatus(StockTransactionStatusType.PREPARED, new Date()));
    StockTransaction st3 = new StockTransaction(StockTransactionType.DESTROY);
    st3.setSource(s1);
    st3.addStatus(new StockTransactionStatus(StockTransactionStatusType.PREPARED, new Date()));
    StockTransaction st4 = new StockTransaction(StockTransactionType.ROLL_IN);
    st4.setDestination(s2);
    StockTransactionStatus status = new StockTransactionStatus(StockTransactionStatusType.PREPARED, new Date());
    status.addParticipation(new StockTransactionParticipation(StockTransactionParticipationType.PICKER, "Hugo"));
    st4.addStatus(status);
    st4.setComment("Muh");
    em.persist(st1);
    em.persist(st2);
    em.persist(st3);
    em.persist(st4);
    tx.commit();
    tx.begin();
    StockTransactionEao stockTransactionEao = new StockTransactionEao(em);
    List<StockTransaction> sts = stockTransactionEao.findByDestination(s1.getId(), StockTransactionType.ROLL_IN, StockTransactionStatusType.PREPARED);
    assertNotNull(sts);
    assertEquals(1, sts.size());
    assertEquals(st2.getId(), sts.get(0).getId());
    sts = stockTransactionEao.findByDestination(s2.getId(), StockTransactionType.ROLL_IN, StockTransactionStatusType.PREPARED, "Hugo", "Muh");
    assertNotNull(sts);
    assertEquals(1, sts.size());
    assertEquals(st4.getId(), sts.get(0).getId());
}
Example 60
Project: eclipselink.runtime-master  File: IdentityTest.java View source code
/**
     * Test identity column value generation.
     */
@Test
public void testIdentity() {
    if (!DBP.supportsIdentity()) {
        return;
    }
    EntityTransaction t = em.getTransaction();
    final Person p1 = new Person("John", "Smith");
    final Person p2 = new Person("Bob", "Brown");
    t.begin();
    try {
        em.persist(p1);
        em.persist(p2);
        t.commit();
    } catch (PersistenceExceptionIllegalArgumentException |  ex) {
        if (t.isActive()) {
            t.rollback();
        }
        ex.printStackTrace();
        throw ex;
    }
    final Map<String, Person> pMap = new HashMap<>(2);
    pMap.put(p1.getSecondName(), p1);
    pMap.put(p2.getSecondName(), p2);
    final TypedQuery<Person> pQuery = em.createQuery("SELECT p FROM Person p", Person.class);
    final List<Person> pList = pQuery.getResultList();
    for (final Person p : pList) {
        final Person pV = pMap.get(p.getSecondName());
        assertEquals(p.getId(), pV.getId());
    }
}
Example 61
Project: eurekastreams-master  File: InsertBulkMapperTest.java View source code
/**
     * Test execute method.
     */
@SuppressWarnings("unchecked")
@Test
public void testExecute() {
    final EntityManager entityManager = context.mock(EntityManager.class);
    final PersistenceListRequest req = context.mock(PersistenceListRequest.class);
    final Session session = context.mock(Session.class);
    final EntityTransaction transaction = context.mock(EntityTransaction.class);
    final List<Activity> activities = new LinkedList<Activity>();
    for (int i = 0; i < NUMOFACTIVITY; i++) {
        activities.add(context.mock(Activity.class, "a" + String.valueOf(i)));
    }
    InsertBulkMapper sut = new InsertBulkMapper();
    sut.setEntityManager(entityManager);
    context.checking(new Expectations() {

        {
            oneOf(req).getDomainEnities();
            will(returnValue(activities));
            oneOf(entityManager).getDelegate();
            will(returnValue(session));
            exactly(NUMOFACTIVITY).of(session).save(with(any(Activity.class)));
            exactly(5).of(session).flush();
            exactly(5).of(session).clear();
            oneOf(entityManager).getTransaction();
            will(returnValue(transaction));
            oneOf(transaction).commit();
            oneOf(session).close();
        }
    });
    assertTrue(sut.execute(req));
    context.assertIsSatisfied();
}
Example 62
Project: fiware-commonsproperties-master  File: PropertiesProviderTxImpl.java View source code
/**
     * @throws InvalidPropertyValueException
     * @throws PropertiesUtilException
     * @see PropertiesUtil#store(Properties, String)
     */
public void store(final Properties prop, final String namespace) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    boolean isActive = true;
    try {
        tx = em.getTransaction();
        if (!tx.isActive()) {
            isActive = false;
            tx.begin();
        }
        createPropertiesProvider(em).store(prop, namespace);
        if (!isActive) {
            tx.commit();
        }
    } finally {
        em.close();
    }
}
Example 63
Project: flexy-pool-master  File: AbstractJavaEEIntegrationTest.java View source code
private <V> V doInTransaction(Callable<V> callable) {
    V result;
    EntityTransaction entityTransaction = null;
    try {
        entityTransaction = entityManager.getTransaction();
        entityTransaction.begin();
        result = callable.call();
        entityTransaction.commit();
        return result;
    } catch (Exception e) {
        if (entityTransaction != null) {
            entityTransaction.rollback();
        }
        throw new IllegalStateException(e);
    }
}
Example 64
Project: gesplan-master  File: JPAUtil.java View source code
public static void closeEntityManager() {
    try {
        EntityManager s = threadEntityManager.get();
        threadEntityManager.set(null);
        if (s != null && s.isOpen()) {
            s.close();
        }
        EntityTransaction tx = threadTransaction.get();
        if (tx != null && tx.isActive()) {
            rollbackTransaction();
            throw new RuntimeException("EntityManager sendo fechado " + "com transação ativa.");
        }
    } catch (RuntimeException ex) {
        throw new InfraestruturaException(ex);
    }
}
Example 65
Project: hibernate-master-class-master  File: AbstractJPATest.java View source code
protected <T> T doInTransaction(TransactionCallable<T> callable) {
    T result = null;
    EntityManager entityManager = null;
    EntityTransaction txn = null;
    try {
        entityManager = entityManagerFactory.createEntityManager();
        txn = entityManager.getTransaction();
        txn.begin();
        result = callable.execute(entityManager);
        txn.commit();
    } catch (RuntimeException e) {
        if (txn != null && txn.isActive())
            txn.rollback();
        throw e;
    } finally {
        if (entityManager != null) {
            entityManager.close();
        }
    }
    return result;
}
Example 66
Project: hibernate-ogm-master  File: JPAResourceLocalTest.java View source code
@Test
public void testBootstrapAndCRUD() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("transaction-type-resource-local", TestHelper.getDefaultTestSettings());
    try {
        final EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            Poem poem = new Poem();
            poem.setName("L'albatros");
            em.persist(poem);
            em.getTransaction().commit();
            em.clear();
            em.getTransaction().begin();
            Poem poem2 = new Poem();
            poem2.setName("Wazaaaaa");
            em.persist(poem2);
            em.flush();
            assertThat(getNumberOfEntities(em)).isEqualTo(2);
            em.getTransaction().rollback();
            assertThat(getNumberOfEntities(em)).isEqualTo(1);
            em.getTransaction().begin();
            poem = em.find(Poem.class, poem.getId());
            assertThat(poem).isNotNull();
            assertThat(poem.getName()).isEqualTo("L'albatros");
            em.remove(poem);
            poem2 = em.find(Poem.class, poem2.getId());
            assertThat(poem2).isNull();
            em.getTransaction().commit();
        } finally {
            EntityTransaction transaction = em.getTransaction();
            if (transaction != null && transaction.isActive()) {
                transaction.rollback();
            }
            em.close();
        }
    } finally {
        dropSchemaAndDatabase(emf);
        emf.close();
    }
}
Example 67
Project: Hibernate-Search-GenericJPA-master  File: MultiQueryAccessTest.java View source code
@Before
public void setup() throws NoSuchFieldException, SQLException {
    this.setup("EclipseLink_MySQL", new MySQLTriggerSQLStringSource());
    this.setupTriggers(new MySQLTriggerSQLStringSource());
    EntityManager em = null;
    try {
        em = this.emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        // hacky, this doesn't belong in the setup method, but whatever
        tx.begin();
        {
            MultiQueryAccess access = this.query(em);
            assertFalse(access.next());
            try {
                access.get();
                fail("expected IllegalStateException");
            } catch (IllegalStateException e) {
            }
        }
        tx.commit();
        System.out.println("passed false MultiQueryAccessTest");
        tx.begin();
        {
            em.createNativeQuery(String.format("INSERT INTO PlaceSorcererUpdatesHsearch(updateid, eventCase, placefk, sorcererfk) VALUES (1, %s, 123123, 123)", String.valueOf(EventType.INSERT))).executeUpdate();
        }
        em.flush();
        {
            em.createNativeQuery(String.format("INSERT INTO PlaceSorcererUpdatesHsearch(updateid, eventCase, placefk, sorcererfk) VALUES (5, %s, 123123, 123)", String.valueOf(EventType.INSERT))).executeUpdate();
        }
        em.flush();
        {
            em.createNativeQuery(String.format("INSERT INTO PlaceSorcererUpdatesHsearch(updateid, eventCase, placefk, sorcererfk) VALUES (4, %s, 123123, 123)", String.valueOf(EventType.UPDATE))).executeUpdate();
        }
        em.flush();
        {
            em.createNativeQuery(String.format("INSERT INTO PlaceUpdatesHsearch(updateid, eventCase, placefk) VALUES (3, %s, 233)", String.valueOf(EventType.UPDATE))).executeUpdate();
        }
        em.flush();
        {
            em.createNativeQuery(String.format("INSERT INTO PlaceUpdatesHsearch(updateid, eventCase, placefk) VALUES (2, %s, 233)", String.valueOf(EventType.DELETE))).executeUpdate();
        }
        em.flush();
        tx.commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
    System.out.println("setup complete!");
}
Example 68
Project: hibernate-search-master  File: SortUsingEntityManagerTest.java View source code
private void createArticles() {
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        em.persist(article(1, "Hibernate & Lucene", date(4, Calendar.JULY, 2005)));
        em.persist(article(2, "Hibernate Search", date(2, Calendar.SEPTEMBER, 2005)));
        em.persist(article(3, "Hibernate OGM", date(4, Calendar.SEPTEMBER, 2005)));
        em.persist(article(4, "Hibernate", date(4, Calendar.DECEMBER, 2005)));
        em.persist(article(5, "Hibernate Validator", date(8, Calendar.SEPTEMBER, 2010)));
        em.persist(article(6, "Hibernate Core", date(4, Calendar.SEPTEMBER, 2012)));
    } finally {
        tx.commit();
        em.clear();
    }
}
Example 69
Project: hibernate4-memcached-master  File: ReadOnlyTest.java View source code
@Test
public void readonly() throws Exception {
    EntityManager em = EntityTestUtils.start();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    log.debug("### First load and save");
    log.debug("person 1 first load.");
    Person person = em.find(Person.class, 1L);
    log.debug("person first load : {}", person);
    Person newPerson = new Person();
    newPerson.setName("Cogito Ergo Sum");
    newPerson.setBirthdate(new Date());
    em.persist(newPerson);
    transaction.commit();
    EntityTestUtils.stop(em);
    log.debug("### Delete!");
    em = EntityTestUtils.start();
    transaction = em.getTransaction();
    transaction.begin();
    log.debug("person 2 delete.");
    Person person2 = em.find(Person.class, newPerson.getId());
    em.remove(person2);
    transaction.commit();
    EntityTestUtils.stop(em);
    try {
        // update시�는 exception 발�.
        log.debug("### Update!");
        em = EntityTestUtils.start();
        transaction = em.getTransaction();
        transaction.begin();
        person = em.find(Person.class, 1L);
        person.setBirthdate(new Date());
        em.merge(person);
        transaction.commit();
    } catch (Exception ex) {
        log.error("Update 중 오류 발�", ex);
    } finally {
        EntityTestUtils.stop(em);
    }
    log.debug("### Delete with query!");
    em = EntityTestUtils.start();
    transaction = em.getTransaction();
    transaction.begin();
    Query query = em.createQuery("delete from Person where id = :id");
    query.setParameter("id", 1L);
    query.executeUpdate();
    transaction.commit();
    EntityTestUtils.stop(em);
}
Example 70
Project: ista.agenda.builder-master  File: DeleteComments.java View source code
/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Gson g = new Gson();
    List<CommentBasic> commentsToDelete = g.fromJson(request.getReader(), new TypeToken<List<CommentBasic>>() {
    }.getType());
    if (commentsToDelete != null) {
        String templateLike = "like on comment: ";
        String templateLiked = "liked on comment: ";
        String templateLiked5 = "liked5 on comment: ";
        CommentsExposedBasic ceb = new CommentsExposedBasic();
        PointsCategoryExposed pce = new PointsCategoryExposed();
        PointsCategory likeCategory = pce.findCategoryByShortName("like");
        PointsCategory likedCategory = pce.findCategoryByShortName("liked");
        PointsCategory liked5Category = pce.findCategoryByShortName("liked5");
        for (CommentBasic commentBasic : commentsToDelete) {
            Comment comment = ceb.getComment(commentBasic.getId());
            EntityManager entityManager = ceb.entityManager;
            EntityTransaction transaction = entityManager.getTransaction();
            transaction.begin();
            comment.getCowner().getComments().remove(comment);
            entityManager.merge(comment.getCowner());
            List<LoggedUser> likedBy = comment.getLikedBy();
            for (LoggedUser loggedUser : likedBy) {
                loggedUser.getLikedComments().remove(comment);
                List<PointsInstance> likesPoints = loggedUser.findAllPointsWithDescription(likeCategory, templateLike);
                removePoints(likeCategory, likesPoints, loggedUser);
                List<PointsInstance> likedPoints = loggedUser.findAllPointsWithDescription(likedCategory, templateLiked);
                removePoints(likedCategory, likedPoints, loggedUser);
                //liked point are removed from the correct user?
                List<PointsInstance> liked5Points = loggedUser.findAllPointsWithDescription(liked5Category, templateLiked5);
                removePoints(liked5Category, liked5Points, loggedUser);
                entityManager.merge(loggedUser);
                entityManager.merge(likeCategory);
                entityManager.merge(likedCategory);
                entityManager.merge(liked5Category);
            }
            entityManager.remove(comment);
            transaction.commit();
        }
    }
}
Example 71
Project: jbasics-master  File: EntityManagerDelegate.java View source code
public void passivate() {
    if (this.manager.isOpen()) {
        // We flush all changes and than clear the manager
        EntityTransaction transaction = this.manager.getTransaction();
        if (transaction != null && transaction.isActive()) {
            this.manager.flush();
        } else {
            this.manager.clear();
        }
    }
}
Example 72
Project: Netuno-master  File: PortoServiceImplTest.java View source code
@Test
public void testSalvar() {
    Porto porto = new Porto();
    porto.setLocalizacao("PA");
    porto.setNome("Par�");
    porto.setAgentes(null);
    porto.setAtraques(null);
    porto.setPatios(null);
    porto.setSlots(null);
    EntityTransaction tx = this.getEntityManager().getTransaction();
    try {
        tx.begin();
        service.salvar(porto);
        tx.commit();
    } catch (Exception e) {
        if (tx.isActive())
            tx.rollback();
        fail("Falha na persist�ncia: " + e.getMessage());
    }
    List<Porto> lista = service.filtrar(porto);
    assertEquals("PA", lista.get(0).getLocalizacao());
}
Example 73
Project: palava-jpa-master  File: TransactionFilter.java View source code
@Override
public Map<String, Object> filter(IpcCall call, IpcCommand command, IpcCallFilterChain chain) throws IpcCommandExecutionException {
    final EntityManager manager = provider.get();
    final EntityTransaction tx = manager.getTransaction();
    LOG.debug("Starting transaction");
    tx.begin();
    final Map<String, Object> result;
    try {
        result = chain.filter(call, command);
    /*CHECKSTYLE:OFF*/
    } catch (RuntimeException e) {
        LOG.error("Execution failed, rolling back", e);
        tx.rollback();
        throw e;
    } catch (IpcCommandExecutionException e) {
        LOG.error("Filtering failed, rolling back", e);
        tx.rollback();
        throw e;
    }
    try {
        assert tx.isActive() : "Transaction should be active";
        tx.commit();
        LOG.debug("Commit succeeded");
        return result;
    } catch (PersistenceException e) {
        LOG.error("Commit failed, rolling back", e);
        tx.rollback();
        throw e;
    }
}
Example 74
Project: REST-OCD-Services-master  File: DatabaseInitializer.java View source code
public CustomGraphId createGraph(CustomGraph graph) {
    graph.setUserName(username);
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        em.persist(graph);
        tx.commit();
    } catch (RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    }
    em.close();
    return new CustomGraphId(graph.getId(), username);
}
Example 75
Project: sneo-master  File: EntityManagerInjectionInterceptor.java View source code
@Override
public String intercept(ActionInvocation invocation) throws Exception {
    Object action = invocation.getAction();
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        for (Class<?> cls = action.getClass(); cls != null; cls = cls.getSuperclass()) {
            if (cls.isAssignableFrom(ActionSupport.class)) {
                break;
            }
            for (Field field : cls.getDeclaredFields()) {
                field.setAccessible(true);
                Object fieldObj = field.get(action);
                if (!(fieldObj instanceof EntityManagerInjectee)) {
                    continue;
                }
                if (em == null) {
                    em = entityManagerFactory.createEntityManager();
                }
                EntityManagerInjectee injectee = (EntityManagerInjectee) fieldObj;
                injectee.setEntityManager(em);
            }
        }
        if (em != null) {
            tx = em.getTransaction();
            tx.begin();
        }
        invocation.addPreResultListener(new Committer(tx));
        String result = invocation.invoke();
        return result;
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}
Example 76
Project: solmix-master  File: EntityManagerFactoryProviderTest.java View source code
@Test
public void nativeUsedEM() {
    EntityManagerFactoryProvider provider = sc.getExtension(EntityManagerFactoryProvider.class);
    EntityManagerFactory emf = provider.createEntityManagerFactory("h2");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    AuthUser au = new AuthUser();
    au.setUserName("superadmin");
    au.setComments("super administrator ,this user can do anything.");
    au.setCreateDate(new Date());
    em.persist(au);
    tx.commit();
    long userId = au.getUserId();
    Assert.assertTrue(userId != 0);
    AuthUser find = em.find(AuthUser.class, userId);
    Assert.assertEquals(au.getUserId(), find.getUserId());
    Assert.assertEquals(au.getUserName(), find.getUserName());
    tx.begin();
    em.remove(find);
    tx.commit();
    em.close();
    Assert.assertNotNull(em);
}
Example 77
Project: spring-data-jpa-master  File: TransactionalInterceptor.java View source code
@AroundInvoke
public Object runInTransaction(InvocationContext ctx) throws Exception {
    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    boolean isNew = !entityTransaction.isActive();
    try {
        if (isNew) {
            entityTransaction.begin();
        }
        Object result = ctx.proceed();
        if (isNew) {
            entityTransaction.commit();
        }
        return result;
    } catch (RuntimeException r) {
        if (isNew) {
            entityTransaction.rollback();
        }
        throw r;
    }
}
Example 78
Project: testfun-master  File: TransactionUtils.java View source code
public static void endTransaction(boolean newTransaction) {
    EntityTransaction tx = getTransaction();
    if (tx.isActive() && newTransaction) {
        if (tx.getRollbackOnly()) {
            // Rollback the transaction and close the connection if roll back was requested deeper in the stack and this is the method starting the transaction
            tx.rollback();
        } else {
            // Commit the transaction only if this is the method starting the transaction and rollback wasn't requested
            tx.commit();
        }
    }
}
Example 79
Project: theone4ever_git-master  File: JpaServlet.java View source code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/plain");
    ServletOutputStream out = response.getOutputStream();
    out.println("@PersistenceUnit=" + emf);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    JpaBean jpaBean = new JpaBean();
    jpaBean.setName("JpaBean");
    em.persist(jpaBean);
    transaction.commit();
    transaction.begin();
    Query query = em.createQuery("SELECT j FROM JpaBean j WHERE j.name='JpaBean'");
    jpaBean = (JpaBean) query.getSingleResult();
    out.println("Loaded " + jpaBean);
    em.remove(jpaBean);
    transaction.commit();
    transaction.begin();
    query = em.createQuery("SELECT count(j) FROM JpaBean j WHERE j.name='JpaBean'");
    int count = ((Number) query.getSingleResult()).intValue();
    if (count == 0) {
        out.println("Removed " + jpaBean);
    } else {
        out.println("ERROR: unable to remove" + jpaBean);
    }
    transaction.commit();
}
Example 80
Project: tomee-master  File: JpaServlet.java View source code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/plain");
    ServletOutputStream out = response.getOutputStream();
    out.println("@PersistenceUnit=" + emf);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    JpaBean jpaBean = new JpaBean();
    jpaBean.setName("JpaBean");
    em.persist(jpaBean);
    transaction.commit();
    transaction.begin();
    Query query = em.createQuery("SELECT j FROM JpaBean j WHERE j.name='JpaBean'");
    jpaBean = (JpaBean) query.getSingleResult();
    out.println("Loaded " + jpaBean);
    em.remove(jpaBean);
    transaction.commit();
    transaction.begin();
    query = em.createQuery("SELECT count(j) FROM JpaBean j WHERE j.name='JpaBean'");
    int count = ((Number) query.getSingleResult()).intValue();
    if (count == 0) {
        out.println("Removed " + jpaBean);
    } else {
        out.println("ERROR: unable to remove" + jpaBean);
    }
    transaction.commit();
}
Example 81
Project: vraptor2_sexy_urls-master  File: JavaPersistenceInterceptor.java View source code
public void intercept(LogicFlow flow) throws LogicException, ViewException {
    ComponentType componentType = flow.getLogicRequest().getLogicDefinition().getComponentType();
    LogicMethod logicMethod = flow.getLogicRequest().getLogicDefinition().getLogicMethod();
    LOG.debug(MessageFormat.format("Preparing PersistenceContext for: {0}", componentType.getName()));
    String persistenceUnitName = introspector.getPersistenceUnitName(componentType);
    LOG.debug(MessageFormat.format("Retrieving the EntityManagerFactory for the PersistenceUnit: {0}.", persistenceUnitName));
    EntityManagerFactory factory;
    synchronized (FACTORIES) {
        factory = FACTORIES.get(persistenceUnitName);
        if (factory == null) {
            LOG.debug(MessageFormat.format("EntityManagerFactory not yet built. Creating one for PersistenceUnit {0}.", persistenceUnitName));
            factory = Persistence.createEntityManagerFactory(persistenceUnitName);
            FACTORIES.put(persistenceUnitName, factory);
        }
    }
    LOG.info("Creating an EntityManager for the request...");
    EntityManager original = factory.createEntityManager();
    this.entityManager = wrap(original);
    try {
        boolean transactionRequired = this.introspector.isTransactionRequired(logicMethod);
        if (transactionRequired) {
            original.getTransaction().begin();
        }
        flow.execute();
        if (transactionRequired && original.getTransaction().isActive() && !original.getTransaction().getRollbackOnly()) {
            original.getTransaction().commit();
        }
    } catch (Throwable t) {
        EntityTransaction transaction = original.getTransaction();
        if (transaction != null && transaction.isActive()) {
            LOG.error("Problem ocurred. The transaction will be rolled back.");
            transaction.rollback();
        }
        throw new LogicException("An error was ocurred. If there were a transaction, it was rolled back.", t);
    } finally {
        LOG.info("Closing the request EntityManager");
        original.close();
    }
}
Example 82
Project: weblounge-master  File: PersistenceUtil.java View source code
public <A> A tx(Function<EntityManager, A> transactional) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        A ret = transactional.apply(em);
        tx.commit();
        return ret;
    } catch (RuntimeException e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw (e);
    } finally {
        em.close();
    }
}
Example 83
Project: werval-master  File: JPAContext.java View source code
private void close(EntityManager em, String persistenceUnitName) {
    if (em.isOpen()) {
        try {
            if (em.isJoinedToTransaction()) {
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    if (!tx.getRollbackOnly()) {
                        LOG.warn("Dangling transaction detected for '{}' persistence unit, it will be rollbacked! - {}", persistenceUnitName, tx);
                    }
                    try {
                        tx.rollback();
                    } catch (Exception ex) {
                        LOG.error("Error rollbacking dangling transaction: {}", ex.getMessage(), ex);
                    }
                }
            }
        } finally {
            em.close();
        }
    }
}
Example 84
Project: wildfly-master  File: SFSB1.java View source code
@TransactionAttribute(TransactionAttributeType.NEVER)
public void createEmployeeNoJTATransaction(String name, String address, int id) {
    EntityManager em = emf.createEntityManager();
    Employee emp = new Employee();
    emp.setId(id);
    emp.setAddress(address);
    emp.setName(name);
    EntityTransaction tx1 = em.getTransaction();
    try {
        tx1.begin();
        em.joinTransaction();
        em.persist(emp);
        tx1.commit();
    } catch (Exception e) {
        throw new RuntimeException("couldn't start tx", e);
    }
}
Example 85
Project: activejpa-master  File: JPAContextTest.java View source code
private EntityTransaction mockTransaction(JPAContext context, boolean active) {
    EntityManager entityManager = context.getEntityManager();
    EntityTransaction txn = mock(EntityTransaction.class);
    when(entityManager.isOpen()).thenReturn(true);
    when(entityManager.getTransaction()).thenReturn(txn);
    when(txn.isActive()).thenReturn(active);
    return txn;
}
Example 86
Project: BatooJPA-master  File: PessimisticLockTest.java View source code
/**
	 * Tests the pessimistic lock.
	 * 
	 * @since 2.0.0
	 */
@Test
public void testPessimisticLockRemove() {
    Foo2 foo = this.newFoo(false);
    this.persist(foo);
    this.commit();
    this.close();
    foo = this.find(Foo2.class, foo.getId(), LockModeType.PESSIMISTIC_WRITE);
    final EntityManager em2 = this.emf().createEntityManager();
    try {
        final Foo2 foo2 = em2.find(Foo2.class, foo.getId(), LockModeType.PESSIMISTIC_WRITE);
        final EntityTransaction tx2 = em2.getTransaction();
        tx2.begin();
        em2.remove(foo2);
        this.begin();
        foo.setValue("test3");
        tx2.commit();
        this.commit();
    } finally {
        em2.close();
    }
}
Example 87
Project: cloudtm-data-platform-master  File: JPAResourceLocalStandaloneTest.java View source code
@Test
public void testJTAStandalone() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpajtastandalone");
    try {
        final EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            Poem poem = new Poem();
            poem.setName("L'albatros");
            em.persist(poem);
            em.getTransaction().commit();
            em.clear();
            em.getTransaction().begin();
            Poem poem2 = new Poem();
            poem2.setName("Wazaaaaa");
            em.persist(poem2);
            em.flush();
            assertThat(assertNumberOfEntities(2, em)).isTrue();
            em.getTransaction().rollback();
            assertThat(assertNumberOfEntities(1, em)).isTrue();
            em.getTransaction().begin();
            poem = em.find(Poem.class, poem.getId());
            assertThat(poem).isNotNull();
            assertThat(poem.getName()).isEqualTo("L'albatros");
            em.remove(poem);
            poem2 = em.find(Poem.class, poem2.getId());
            assertThat(poem2).isNull();
            em.getTransaction().commit();
        } finally {
            EntityTransaction transaction = em.getTransaction();
            if (transaction != null && transaction.isActive()) {
                transaction.rollback();
            }
            em.close();
        }
    } finally {
        dropSchemaAndDatabase(emf);
        emf.close();
    }
}
Example 88
Project: easybatch-framework-master  File: JpaRecordWriter.java View source code
@Override
public void writeRecords(Batch batch) throws Exception {
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    try {
        for (Record record : batch) {
            entityManager.persist(record.getPayload());
        }
        entityManager.flush();
        entityManager.clear();
        transaction.commit();
        LOGGER.info("Transaction committed");
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Unable to commit transaction", e);
        transaction.rollback();
        LOGGER.info("Transaction rolled back");
    }
}
Example 89
Project: grantmaster-master  File: DatabaseSingleton.java View source code
public boolean transaction(TransactionRunner runner) {
    EntityManagerFactory entityManagerFactory = getEntityManagerFactory();
    if (entityManagerFactory == null) {
        return false;
    }
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        if (runner.run(entityManager)) {
            transaction.commit();
        } else {
            if (transaction.isActive()) {
                // It may already be rolled back.
                transaction.rollback();
            }
            return false;
        }
    } catch (Throwable t) {
        LoggerFactory.getLogger(DatabaseSingleton.class).error(null, t);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        return false;
    } finally {
        entityManager.close();
        Utils.logMemoryUsage("after transaction");
    }
    connection.setUnsavedChanges(true);
    return true;
}
Example 90
Project: hibernate-core-ogm-master  File: DeleteOrphanTest.java View source code
@Test
public void testDeleteOrphan() throws Exception {
    EntityTransaction tx;
    EntityManager em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    Troop disney = new Troop();
    disney.setName("Disney");
    Soldier mickey = new Soldier();
    mickey.setName("Mickey");
    disney.addSoldier(mickey);
    em.persist(disney);
    tx.commit();
    em.close();
    em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    Troop troop = em.find(Troop.class, disney.getId());
    Hibernate.initialize(troop.getSoldiers());
    tx.commit();
    em.close();
    Soldier soldier = troop.getSoldiers().iterator().next();
    troop.getSoldiers().remove(soldier);
    troop = (Troop) deserialize(serialize(troop));
    em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    em.merge(troop);
    tx.commit();
    em.close();
    em = getOrCreateEntityManager();
    tx = em.getTransaction();
    tx.begin();
    soldier = em.find(Soldier.class, mickey.getId());
    Assert.assertNull("delete-orphan should work", soldier);
    troop = em.find(Troop.class, disney.getId());
    em.remove(troop);
    tx.commit();
    em.close();
}
Example 91
Project: IBE-Secure-Message-master  File: CommonDAOImpl.java View source code
/*
	 * (non-Javadoc)
	 * @see hamaster.gradesign.idmgmt.CommonDAO#save(java.util.Collection)
	 */
@Override
public void batchSave(Collection<?> entities) {
    EntityManager manager = factory.createEntityManager();
    FlushModeType orig = manager.getFlushMode();
    manager.setFlushMode(FlushModeType.COMMIT);
    EntityTransaction et = manager.getTransaction();
    et.begin();
    for (Object entity : entities) manager.persist(entity);
    et.commit();
    manager.setFlushMode(orig);
}
Example 92
Project: ilves-master  File: UserDirectoryDao.java View source code
/**
     * Adds userDirectory to database.
     * @param entityManager the entity manager
     * @param userDirectory the userDirectory
     */
protected static final void addUserDirectory(final EntityManager entityManager, final UserDirectory userDirectory) {
    final EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    try {
        entityManager.persist(userDirectory);
        transaction.commit();
    } catch (final Exception e) {
        LOG.error("Error in add userDirectory.", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new RuntimeException(e);
    }
}
Example 93
Project: juddi-master  File: JPAUtil.java View source code
//REMOVE Comment from Code Review: This class does not seem to be in use. Do we need it?
public static void persistEntity(Object uddiEntity, Object entityKey) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Object existingUddiEntity = em.find(uddiEntity.getClass(), entityKey);
        if (existingUddiEntity != null)
            em.remove(existingUddiEntity);
        em.persist(uddiEntity);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Example 94
Project: LFS-Racecontrol-master  File: DatabasePersistence.java View source code
public <T> T store(T object) throws PersistenceException {
    log.debug("store: " + object);
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    object = entityManager.merge(object);
    transaction.commit();
    entityManager.close();
    return object;
}
Example 95
Project: lobbyservice-master  File: UrlNameUtils.java View source code
/** update UrlName mapping for GameTemplate(s) */
public static void updateGameTemplateUrlName(GameTemplate gameTemplate) {
    // check new url name
    String urlName = gameTemplate.getUrlName();
    // quick check on old url name
    EntityManager em = EMF.get().createEntityManager();
    EntityTransaction et = em.getTransaction();
    GameTemplateUrlName gtun = null;
    try {
        if (urlName != null) {
            Key key = GameTemplateUrlName.urlNameToKey(urlName);
            et.begin();
            em.find(GameTemplateUrlName.class, key);
            if (gtun != null) {
                // still ours?
                if (!gtun.getGameTemplateKey().equals(gameTemplate.getKey())) {
                    logger.warning("GameTemplateUrlName '" + urlName + "' owned by another template: " + gtun.getGameTemplateKey().getName());
                    gtun = null;
                } else {
                // already ours
                }
                et.rollback();
            } else {
                // create atomic
                gtun = new GameTemplateUrlName();
                gtun.setKey(key);
                gtun.setGameTemplateKey(gameTemplate.getKey());
                em.persist(gtun);
                et.commit();
            }
        }
    } finally {
        if (et.isActive())
            et.rollback();
        em.close();
    }
    // tidy up
    em = EMF.get().createEntityManager();
    try {
        Query q = em.createQuery("SELECT x FROM GameTemplateUrlName x WHERE x." + GAME_TEMPLATE_KEY + " = :" + GAME_TEMPLATE_KEY);
        List<GameTemplateUrlName> gtuns = (List<GameTemplateUrlName>) q.getResultList();
        for (GameTemplateUrlName gtun2 : gtuns) {
            if (urlName == null || !urlName.equals(gtun2.getKey().getName()))
                // not sure how to play this with transactions becuase of lazy load of list vs remove
                em.remove(gtun2);
        }
    } finally {
        em.close();
    }
// TODO Auto-generated method stub
}
Example 96
Project: moskito-central-master  File: PSQLStorage.java View source code
@Override
public void processSnapshot(Snapshot target) {
    String producerId = target.getMetaData().getProducerId();
    String interval = target.getMetaData().getIntervalName();
    if (!config.include(producerId, interval)) {
        return;
    }
    Class<? extends StatisticsEntity> statEntityClass = config.getStatEntityClassName(target.getMetaData().getStatClassName(), producerId);
    if (statEntityClass == null) {
        statEntityClass = JSONStatisticsEntity.class;
    }
    SnapshotEntity entity = new SnapshotEntity();
    entity.setProducerId(producerId);
    entity.setCategory(target.getMetaData().getCategory());
    entity.setSubsystem(target.getMetaData().getSubsystem());
    entity.setIntervalName(interval);
    entity.setComponentName(target.getMetaData().getComponentName());
    entity.setHostName(target.getMetaData().getHostName());
    entity.setCreationTimestamp(target.getMetaData().getCreationTimestamp());
    for (String key : target.getKeySet()) {
        StatisticsEntity entityInstance = null;
        try {
            entityInstance = statEntityClass.newInstance();
        } catch (IllegalAccessException e) {
            log.error("Instance cannot be instantiated", e);
            continue;
        } catch (InstantiationException e) {
            log.error("Instance cannot be instantiated", e);
            continue;
        }
        entityInstance.setStats(target.getStatistics(key));
        entity.addStatistics(key, entityInstance);
    }
    EntityManager manager = null;
    EntityTransaction tr = null;
    try {
        manager = factory.createEntityManager();
        tr = manager.getTransaction();
        tr.begin();
        manager.persist(entity);
        tr.commit();
    } catch (Exception e) {
        log.error("persist failed", e);
        if (tr != null) {
            tr.rollback();
        }
    } finally {
        if (manager != null) {
            manager.close();
        }
    }
}
Example 97
Project: opencast-master  File: PersistenceUtil.java View source code
@Override
public <A> A tx(Function<EntityManager, A> transactional) {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        A ret = transactional.apply(em);
        tx.commit();
        return ret;
    } catch (RuntimeException e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw (e);
    } finally {
        if (em != null)
            em.close();
    }
}
Example 98
Project: palava-jpa-aspectj-master  File: EntityTransactionAspect.java View source code
// CHECKSTYLE:OFF
@Around("execution(@de.cosmocode.palava.jpa.Transactional * *.*(..))")
public Object transactional(ProceedingJoinPoint point) {
    checkInjected();
    final EntityManager manager = currentManager.get();
    LOG.trace("Retrieved entitymanager {}", manager);
    final EntityTransaction tx = manager.getTransaction();
    LOG.trace("Using transaction {}", tx);
    final boolean local = !tx.isActive();
    if (local) {
        LOG.debug("Beginning automatic transaction {}", tx);
        tx.begin();
    } else {
        LOG.trace("Transaction {} already active", tx);
    }
    final Object returnValue;
    try {
        returnValue = point.proceed();
    } catch (Throwable e) {
        try {
            if (local && (tx.isActive() || tx.getRollbackOnly())) {
                LOG.debug("Rolling back local/active transaction {}", tx);
                tx.rollback();
            } else if (!tx.getRollbackOnly()) {
                LOG.debug("Setting transaction {} as rollback only", tx);
                tx.setRollbackOnly();
            }
        } catch (PersistenceException inner) {
            LOG.error("Rollback failed", inner);
        } finally {
            throw Throwables.sneakyThrow(e);
        }
    }
    if (local && tx.isActive()) {
        if (tx.getRollbackOnly()) {
            LOG.debug("Rolling back marked transaction {}", tx);
            tx.rollback();
        } else {
            try {
                tx.commit();
                LOG.debug("Committed automatic transaction {}", tx);
            } catch (PersistenceException e) {
                if (tx.isActive()) {
                    try {
                        LOG.debug("Rolling back transaction {}", tx);
                        tx.rollback();
                    } catch (PersistenceException inner) {
                        LOG.error("Rollback failed", inner);
                    }
                }
                throw e;
            }
        }
    } else {
        LOG.trace("Not committing non-local transaction {}", tx);
    }
    return returnValue;
}
Example 99
Project: pm-persistence-utils-master  File: JpaGuicePersistenceTransaction.java View source code
public void end() {
    if (!started.get())
        throw new RuntimeException("transaction not started");
    try {
        EntityTransaction transaction = emp.get().getTransaction();
        PersistenceTransactionSynchronization.Status status;
        if (transaction.getRollbackOnly()) {
            transaction.rollback();
            log.trace("Jpa transaction rolledback");
            status = Status.ROLLEDBACK;
        } else {
            transaction.commit();
            log.trace("Jpa transaction committed");
            status = Status.COMMITTED;
        }
        if (sync.get() != null) {
            for (PersistenceTransactionSynchronization s : sync.get()) {
                s.afterTransaction(status);
            }
        }
    } finally {
        sync.remove();
        try {
            unitOfWork.end();
        } finally {
            started.remove();
        }
    }
}
Example 100
Project: rome-certiorem-master  File: JPADAO.java View source code
@Override
public List<? extends Subscriber> subscribersForTopic(final String topic) {
    final LinkedList<JPASubscriber> result = new LinkedList<JPASubscriber>();
    final EntityManager em = factory.createEntityManager();
    final EntityTransaction tx = em.getTransaction();
    tx.begin();
    final Query query = em.createNamedQuery("Subcriber.forTopic");
    query.setParameter("topic", topic);
    try {
        @SuppressWarnings("unchecked") final List<JPASubscriber> subscribers = query.getResultList();
        for (final JPASubscriber subscriber : subscribers) {
            if (subscriber.getLeaseSeconds() == -1) {
                result.add(subscriber);
                continue;
            }
            if (subscriber.getSubscribedAt().getTime() < System.currentTimeMillis() - 1000 * subscriber.getLeaseSeconds()) {
                subscriber.setExpired(true);
            } else {
                result.add(subscriber);
            }
            if (subscriber.isExpired() && purgeExpired) {
                em.remove(subscriber);
            }
        }
    } catch (final NoResultException e) {
        tx.rollback();
        em.close();
        return result;
    }
    if (!tx.getRollbackOnly()) {
        tx.commit();
    } else {
        tx.rollback();
    }
    em.close();
    return result;
}
Example 101
Project: rome-master  File: JPADAO.java View source code
@Override
public List<? extends Subscriber> subscribersForTopic(final String topic) {
    final LinkedList<JPASubscriber> result = new LinkedList<JPASubscriber>();
    final EntityManager em = factory.createEntityManager();
    final EntityTransaction tx = em.getTransaction();
    tx.begin();
    final Query query = em.createNamedQuery("Subcriber.forTopic");
    query.setParameter("topic", topic);
    try {
        @SuppressWarnings("unchecked") final List<JPASubscriber> subscribers = query.getResultList();
        for (final JPASubscriber subscriber : subscribers) {
            if (subscriber.getLeaseSeconds() == -1) {
                result.add(subscriber);
                continue;
            }
            if (subscriber.getSubscribedAt().getTime() < System.currentTimeMillis() - 1000 * subscriber.getLeaseSeconds()) {
                subscriber.setExpired(true);
            } else {
                result.add(subscriber);
            }
            if (subscriber.isExpired() && purgeExpired) {
                em.remove(subscriber);
            }
        }
    } catch (final NoResultException e) {
        tx.rollback();
        em.close();
        return result;
    }
    if (!tx.getRollbackOnly()) {
        tx.commit();
    } else {
        tx.rollback();
    }
    em.close();
    return result;
}