Java Code Examples for javax.persistence.EntityManager#close()

The following examples show how to use javax.persistence.EntityManager#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InvoiceDB.java    From MusicStore with MIT License 7 votes vote down vote up
/**
 * Updates the invoice object in the database
 *
 * @param invoice The object to be updated
 */
public static void update(Invoice invoice) {
   EntityManager em = DBUtil.getEmFactory().createEntityManager();
   EntityTransaction transaction = em.getTransaction();

   try {
      transaction.begin();
      em.merge(invoice);
      transaction.commit();
   } catch (Exception e) {
      System.out.println(e);
      transaction.rollback();
   } finally {
      em.close();
   }
}
 
Example 2
Source File: TestEnum.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void persistAndLoad() {
	log.info("... persistAndLoad ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	Author a = new Author();
	a.setFirstName("John");
	a.setLastName("Doe");
	a.setStatus(AuthorStatus.PUBLISHED);
	
	em.persist(a);
	
	em.getTransaction().commit();
	em.close();
	
	em = emf.createEntityManager();
	em.getTransaction().begin();

	a = em.find(Author.class, a.getId());
	log.info(a);
	
	em.getTransaction().commit();
	em.close();
}
 
Example 3
Source File: SubscriberDao.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public void update( final String environmentId, final String subscriberId ) throws DaoException
{
    EntityManager em = emf.createEntityManager();
    try
    {
        em.getTransaction().begin();

        Subscriber subscriber = new Subscriber( environmentId, subscriberId );
        em.merge( subscriber );

        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOGGER.error( "Instance is not an entity or command invoked on a container-managed entity manager." );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
        throw new DaoException( e );
    }
    finally
    {
        em.close();
    }
}
 
Example 4
Source File: JpaTest.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        // 1、获取EntityManager
        em = JpaUtil.getEntityManager();
        // 2、获取事务
        tx = em.getTransaction();
        // 3、开启事务
        tx.begin();
        // 4、获取数据、删除数据
        // primaryKey类型必须和实体主键类型一致,否则查询不到
        Customer customer = em.find(Customer.class, 2L);
        System.out.println(customer);
        // 5、提交事务
        tx.commit();
    } catch (Exception e) {
        if (tx != null) tx.rollback();
    } finally {
        if (em != null) em.close();
    }
}
 
Example 5
Source File: DatabaseAccessTokenStorage.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Override
public IAccessTokenInfo refreshToken(String oldAccessToken, String newAccessToken, String newRefreshToken) throws TokenStorageException {
	try {
		EntityManager em = emf.createEntityManager();
		try {
			TokenEntity tokenEntity = em.find(TokenEntity.class, oldAccessToken);
			removeToken(em, tokenEntity);
			
			tokenEntity.updateTokens(newAccessToken, newRefreshToken);
			saveTokenEntity(tokenEntity);
			setUser(tokenEntity);
			return tokenEntity;
		} finally {
			em.close();
		}
	} catch (UserStorageServiceException | PersistenceException e) {
		throw new TokenStorageException(e);
	}
}
 
Example 6
Source File: JPATest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void testSaveAndLoad() {
	final PurchaseOrderType alpha = objectFactory.createPurchaseOrderType();
	alpha.setShipTo(objectFactory.createUSAddress());
	alpha.getShipTo().setCity("Sacramento");

	final EntityManager saveManager = entityManagerFactory
			.createEntityManager();
	saveManager.getTransaction().begin();
	saveManager.persist(alpha);
	saveManager.getTransaction().commit();
	saveManager.close();

	final Long id = alpha.getHjid();

	final EntityManager loadManager = entityManagerFactory
			.createEntityManager();
	final PurchaseOrderType beta = loadManager.find(
			PurchaseOrderType.class, id);
	loadManager.close();
	// Check that we're still shipping to Sacramento
	assertEquals("Sacramento", beta.getShipTo().getCity());

}
 
Example 7
Source File: UpdateDao.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public void persist( final UpdateEntity item )
{
    EntityManager em = emf.createEntityManager();
    try
    {
        em.getTransaction().begin();
        em.persist( item );
        em.flush();
        em.refresh( item );
        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOG.error( e.toString(), e );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
    }
    finally
    {
        em.close();
    }
}
 
Example 8
Source File: HikeQueryTest.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpEntityManagerFactory() {
	entityManagerFactory = Persistence.createEntityManagerFactory( "hikePu" );

	EntityManager entityManager = entityManagerFactory.createEntityManager();

	entityManager.getTransaction().begin();

	// create a Person
	Person bob = new Person( "Bob", "McRobb" );

	// and two hikes
	Hike cornwall = new Hike(
			"Visiting Land's End", new Date(), new BigDecimal( "5.5" ),
			new HikeSection( "Penzance", "Mousehole" ),
			new HikeSection( "Mousehole", "St. Levan" ),
			new HikeSection( "St. Levan", "Land's End" )
	);
	Hike isleOfWight = new Hike(
			"Exploring Carisbrooke Castle", new Date(), new BigDecimal( "7.5" ),
			new HikeSection( "Freshwater", "Calbourne" ),
			new HikeSection( "Calbourne", "Carisbrooke Castle" )
	);

	// let Bob organize the two hikes
	cornwall.setOrganizer( bob );
	bob.getOrganizedHikes().add( cornwall );

	isleOfWight.setOrganizer( bob );
	bob.getOrganizedHikes().add( isleOfWight );

	// persist organizer (will be cascaded to hikes)
	entityManager.persist( bob );

	entityManager.getTransaction().commit();

	// get a new EM to make sure data is actually retrieved from the store and not Hibernate’s internal cache
	entityManager.close();
}
 
Example 9
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void storeTestCitizens(final EntityManagerFactory emf, Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    em.persist(new Citizen("Aria", "Stark", "45989213T"));
    em.persist(new Citizen("Jon", "Snow", "96246496Y"));
    em.persist(new Citizen("Tyrion", "Lannister", "09287101T"));
    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
Example 10
Source File: JPAWorkItemHandlerTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
private Product create(Product newProd) throws Exception {
    ut.begin();
    EntityManager em = emf.createEntityManager();
    em.persist(newProd);
    em.close();
    ut.commit();
    return newProd;
}
 
Example 11
Source File: MCRSessionContext.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Closes Session if Session is still open.
 */
private void autoCloseSession(EntityManager currentEntityManager) {
    if (currentEntityManager != null && currentEntityManager.isOpen()) {
        LOGGER.debug("Autoclosing current JPA EntityManager");
        currentEntityManager.close();
    }
}
 
Example 12
Source File: ValidateValueSetValidation.java    From juddi with Apache License 2.0 5 votes vote down vote up
public static Tmodel GetTModel_MODEL_IfExists(String tmodelKey) throws ValueNotAllowedException {
        EntityManager em = PersistenceManager.getEntityManager();

        Tmodel model = null;
        if (em == null) {
                //this is normally the Install class firing up
                log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
                return null;
        } else {


                EntityTransaction tx = em.getTransaction();
                try {
                        
                        tx.begin();
                        model = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
                        tx.commit();
                } finally {
                        if (tx.isActive()) {
                                tx.rollback();
                        }
                        em.close();
                }

        }
        return model;
}
 
Example 13
Source File: ApplicationManagedEntityManagerIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public void testEntityManagerProxyIsProxy() {
	EntityManager em = entityManagerFactory.createEntityManager();
	assertTrue(Proxy.isProxyClass(em.getClass()));
	Query q = em.createQuery("select p from Person as p");
	List<Person> people = q.getResultList();
	assertNotNull(people);

	assertTrue("Should be open to start with", em.isOpen());
	em.close();
	assertFalse("Close should work on application managed EM", em.isOpen());
}
 
Example 14
Source File: ReplicationNotifier.java    From juddi with Apache License 2.0 5 votes vote down vote up
/**
 * returns the latest version of the replication config or null if there
 * is no config
 *
 * @return
 */
public static org.uddi.repl_v3.ReplicationConfiguration FetchEdges() {

        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = null;
        org.uddi.repl_v3.ReplicationConfiguration item = new org.uddi.repl_v3.ReplicationConfiguration();
        try {
                tx = em.getTransaction();
                tx.begin();
                Query q = em.createQuery("SELECT item FROM ReplicationConfiguration item order by item.serialNumber DESC");
                q.setMaxResults(1);
                ReplicationConfiguration results = (ReplicationConfiguration) q.getSingleResult();
                //   ReplicationConfiguration find = em.find(ReplicationConfiguration.class, null);
                if (results != null) {
                        MappingModelToApi.mapReplicationConfiguration(results, item);
                }

                tx.commit();
                return item;
        } catch (Exception ex) {
                //log.error("error", ex);
                //no config available
                if (tx != null && tx.isActive()) {
                        tx.rollback();
                }
        } finally {
                em.close();
        }
        return null;
}
 
Example 15
Source File: AbstractRepository.java    From msf4j with Apache License 2.0 5 votes vote down vote up
protected void remove(T t) {
    EntityManager manager = getEntityManager();
    manager.getTransaction().begin();
    manager.remove(t);
    manager.getTransaction().commit();
    manager.close();
}
 
Example 16
Source File: AbstractDatabaseTest.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Before
public void clearTableUnderTest() {
    EntityManager manager = factory.createEntityManager();
    manager.getTransaction().begin();

    manager.createQuery("delete from " + tableType.getSimpleName()).executeUpdate();
    manager.getTransaction().commit();
    manager.close();
}
 
Example 17
Source File: DateTimeEntityRepository.java    From tutorials with MIT License 5 votes vote down vote up
public void save(Long id) {
    JPA22DateTimeEntity dateTimeTypes = new JPA22DateTimeEntity();
    dateTimeTypes.setId(id);

    //java.sql types: date/time
    dateTimeTypes.setSqlTime(Time.valueOf(LocalTime.now()));
    dateTimeTypes.setSqlDate(Date.valueOf(LocalDate.now()));
    dateTimeTypes.setSqlTimestamp(Timestamp.valueOf(LocalDateTime.now()));

    //java.util types: date/calendar
    java.util.Date date = new java.util.Date();
    dateTimeTypes.setUtilTime(date);
    dateTimeTypes.setUtilDate(date);
    dateTimeTypes.setUtilTimestamp(date);

    //Calendar
    Calendar calendar = Calendar.getInstance();
    dateTimeTypes.setCalendarTime(calendar);
    dateTimeTypes.setCalendarDate(calendar);
    dateTimeTypes.setCalendarTimestamp(calendar);

    //java.time types
    dateTimeTypes.setLocalTime(LocalTime.now());
    dateTimeTypes.setLocalDate(LocalDate.now());
    dateTimeTypes.setLocalDateTime(LocalDateTime.now());

    //java.time types with offset
    dateTimeTypes.setOffsetTime(OffsetTime.now());
    dateTimeTypes.setOffsetDateTime(OffsetDateTime.now());

    EntityManager entityManager = emf.createEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist(dateTimeTypes);
    entityManager.getTransaction().commit();
    entityManager.close();
}
 
Example 18
Source File: TestEntityManagerProducer.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
protected void closeEntityManager(@Disposes EntityManager entityManager)
{
    if (entityManager.isOpen())
    {
        entityManager.close();
    }
    closeEntityManagerCount++;
}
 
Example 19
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used for updating a entity. It uses HTTP PUT method.
 *
 * @param place the entity to be updated.
 * @return The updated entity.
 */
public Place update(Place place, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(place);
  } finally {
    mgr.close();
  }
  return place;
}
 
Example 20
Source File: UDDICustodyTransferImpl.java    From juddi with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void discardTransferToken(DiscardTransferToken body)
        throws DispositionReportFaultMessage {
        long startTime = System.currentTimeMillis();

        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
                tx.begin();

                UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

                new ValidateCustodyTransfer(publisher).validateDiscardTransferToken(em, body);

                org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
                if (apiTransferToken != null) {
                        String transferTokenId;
                        try {
                            transferTokenId = new String(apiTransferToken.getOpaqueToken(), UTF8);
                        } catch (UnsupportedEncodingException ex) {
                            throw new InvalidValueException(new ErrorMessage("errors.stringEncoding"));
                        }
                        org.apache.juddi.model.TransferToken modelTransferToken = em.find(org.apache.juddi.model.TransferToken.class, transferTokenId);
                        if (modelTransferToken != null) {
                                em.remove(modelTransferToken);
                        }
                }

                KeyBag keyBag = body.getKeyBag();
                if (keyBag != null) {
                        List<String> keyList = keyBag.getKey();
                        Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(0);
                        for (String key : keyList) {
                                // Creating parameters for key-checking query
                                DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)",
                                        key.toUpperCase(),
                                        DynamicQuery.PREDICATE_EQUALS);

                                params.add(param);
                        }

                        // Find the associated transfer tokens and remove them.
                        DynamicQuery getTokensQry = new DynamicQuery();
                        getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad();
                        getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0]));

                        Query qry = getTokensQry.buildJPAQuery(em);
                        List<org.apache.juddi.model.TransferToken> tokensToDelete = qry.getResultList();
                        if (tokensToDelete != null && tokensToDelete.size() > 0) {
                                for (org.apache.juddi.model.TransferToken tt : tokensToDelete) {
                                        em.remove(tt);
                                }
                        }
                }

                tx.commit();
                long procTime = System.currentTimeMillis() - startTime;
                serviceCounter.update(CustodyTransferQuery.DISCARD_TRANSFERTOKEN,
                        QueryStatus.SUCCESS, procTime);

        } finally {
                if (tx.isActive()) {
                        tx.rollback();
                }
                em.close();
        }
}