下面列出了javax.persistence.EntityManager#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
}
@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();
}
}
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();
}
}
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());
}
@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);
}
}
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();
}
}
@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();
}
@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());
}
/**
* 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;
}
protected void closeEntityManager(@Disposes EntityManager entityManager)
{
if (entityManager.isOpen())
{
entityManager.close();
}
closeEntityManagerCount++;
}
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();
}
@Before
public void clearTableUnderTest() {
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
manager.createQuery("delete from " + tableType.getSimpleName()).executeUpdate();
manager.getTransaction().commit();
manager.close();
}
protected void remove(T t) {
EntityManager manager = getEntityManager();
manager.getTransaction().begin();
manager.remove(t);
manager.getTransaction().commit();
manager.close();
}
/**
* 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;
}
@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();
}
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;
}
/**
* 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();
}
}
private Product create(Product newProd) throws Exception {
ut.begin();
EntityManager em = emf.createEntityManager();
em.persist(newProd);
em.close();
ut.commit();
return newProd;
}
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);
}
@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();
}
}