javax.persistence.EntityManager.close()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(350)

本文整理了Java中javax.persistence.EntityManager.close()方法的一些代码示例,展示了EntityManager.close()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。EntityManager.close()方法的具体详情如下:
包路径:javax.persistence.EntityManager
类名称:EntityManager
方法名:close

EntityManager.close介绍

[英]Close an application-managed entity manager. After the close method has been invoked, all methods on the EntityManager instance and any Query and TypedQuery objects obtained from it will throw the IllegalStateException except for getProperties, getTransaction, and isOpen (which will return false). If this method is called when the entity manager is associated with an active transaction, the persistence context remains managed until the transaction completes.
[中]关闭应用程序管理的实体管理器。调用close方法后,EntityManager实例上的所有方法以及从中获得的任何QueryTypedQuery对象将抛出IllegalStateException,除了getPropertiesgetTransactionisOpen(这将返回false)。如果在实体管理器与活动事务关联时调用此方法,则持久性上下文将保持管理状态,直到事务完成。

代码示例

代码示例来源:origin: spring-projects/spring-data-jpa

/**
 * Returns whether the named query with the given name exists.
 *
 * @param em must not be {@literal null}.
 * @param queryName must not be {@literal null}.
 * @return
 */
private static boolean hasNamedQuery(EntityManager em, String queryName) {
  /*
   * See DATAJPA-617, we have to use a dedicated em for the lookups to avoid a
   * potential rollback of the running tx.
   */
  EntityManager lookupEm = em.getEntityManagerFactory().createEntityManager();
  try {
    lookupEm.createNamedQuery(queryName);
    return true;
  } catch (IllegalArgumentException e) {
    LOG.debug("Did not find named query {}", queryName);
    return false;
  } finally {
    lookupEm.close();
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testEntityManagerFactory2() {
  EntityManager em = this.entityManagerFactory2.createEntityManager();
  try {
    em.createQuery("select tb from TestBean");
    fail("Should have thrown IllegalArgumentException");
  }
  catch (IllegalArgumentException ex) {
    // expected
  }
  finally {
    em.close();
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void deferredQueryWithResultList() {
  EntityManagerFactory emf = mock(EntityManagerFactory.class);
  EntityManager targetEm = mock(EntityManager.class);
  Query query = mock(Query.class);
  given(emf.createEntityManager()).willReturn(targetEm);
  given(targetEm.createQuery("x")).willReturn(query);
  given(targetEm.isOpen()).willReturn(true);
  EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
  em.createQuery("x").getResultList();
  verify(query).getResultList();
  verify(targetEm).close();
}

代码示例来源:origin: Impetus/Kundera

private void findByNameAndAgeWithOrClause()
{
  EntityManager em;
  String query;
  Query q;
  List<StudentCouchDBChar> students;
  int count;
  em = emf.createEntityManager();
  query = "Select s From StudentOracleNoSQLChar s where s.name = Kuldeep and s.age > " + getMinValue(short.class);
  q = em.createQuery(query);
  students = q.getResultList();
  Assert.assertNotNull(students);
  Assert.assertEquals(1, students.size());
  count = 0;
  for (StudentCouchDBChar student : students)
  {
    Assert.assertEquals(getMaxValue(char.class), student.getId());
    Assert.assertEquals(getMaxValue(short.class), student.getAge());
    Assert.assertEquals("Kuldeep", student.getName());
    count++;
  }
  Assert.assertEquals(1, count);
  em.close();
}

代码示例来源:origin: kiegroup/jbpm

@Override
public Object findContextId(Long ksessionId, String ownerId) {
  EntityManagerInfo info = getEntityManager(null);
  EntityManager em = info.getEntityManager();
  try {
    Query findQuery = em.createNamedQuery("FindContextMapingByKSessionId")
        .setParameter("ksessionId", ksessionId)
        .setParameter("ownerId", ownerId);
    @SuppressWarnings("unchecked")
    List<ContextMappingInfo> contextMapping = findQuery.getResultList();
    if (contextMapping.isEmpty()) {
      return null;
    } else if (contextMapping.size() == 1) {
      return contextMapping.get(0).getContextId();
    } else {
      return contextMapping.stream().map(cmi -> cmi.getContextId()).collect(Collectors.toList());
    }
  } catch (NoResultException e) {
    return null;
  } catch (NonUniqueResultException e) {
    return null;
  } finally {
    if (!info.isShared()) {
      em.close();
    }
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testJpaEnvers() throws Exception {
  final ServiceReference serviceReference = bundleContext.getServiceReference( PersistenceProvider.class.getName() );
  final PersistenceProvider persistenceProvider = (PersistenceProvider) bundleContext.getService( serviceReference );
  final EntityManagerFactory emf = persistenceProvider.createEntityManagerFactory( "hibernate-osgi-test", null );
  final Integer adpId;
  EntityManager em = emf.createEntityManager();
  em.getTransaction().begin();
  AuditedDataPoint adp = new AuditedDataPoint( "Chris" );
  em.persist( adp );
  em.getTransaction().commit();
  adpId = adp.getId();
  em.close();
  em = emf.createEntityManager();
  em.getTransaction().begin();
  adp = em.find( AuditedDataPoint.class, adpId );
  adp.setName( "Chris2" );
  em.getTransaction().commit();
  em.close();
  em = emf.createEntityManager();
  AuditReader ar = AuditReaderFactory.get( em );
  assertEquals( 2, ar.getRevisions( AuditedDataPoint.class, adpId ).size() );
  AuditedDataPoint rev1 = ar.find( AuditedDataPoint.class, adpId, 1 );
  AuditedDataPoint rev2 = ar.find( AuditedDataPoint.class, adpId, 2 );
  assertEquals( new AuditedDataPoint( adpId, "Chris" ), rev1 );
  assertEquals( new AuditedDataPoint( adpId, "Chris2" ), rev2 );
  em.close();
}

代码示例来源:origin: Impetus/Kundera

public void testFindById(boolean useSameEm)
{
  EntityManager em = emf.createEntityManager();
  StudentMongoCalendar studentMax = em.find(StudentMongoCalendar.class, getMaxValue(Calendar.class));
  Assert.assertNotNull(studentMax);
  Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());
  Assert.assertEquals(getMaxValue(String.class), studentMax.getName());
  em.close();
}

代码示例来源:origin: spring-projects/spring-framework

@Test
@SuppressWarnings("unchecked")
public void testEntityManagerProxyIsProxy() {
  assertTrue(Proxy.isProxyClass(sharedEntityManager.getClass()));
  Query q = sharedEntityManager.createQuery("select p from Person as p");
  q.getResultList();
  assertTrue("Should be open to start with", sharedEntityManager.isOpen());
  sharedEntityManager.close();
  assertTrue("Close should have been silently ignored", sharedEntityManager.isOpen());
}

代码示例来源:origin: Impetus/Kundera

public void deleteCounter()
{
  EntityManager em = emf.createEntityManager();
  Counters counters = new Counters();
  counters = em.find(Counters.class, id3);
  Assert.assertNotNull(counters);
  Assert.assertNotNull(counters.getCounter());
  em.remove(counters);
  EntityManager em1 = emf.createEntityManager();
  counters = em1.find(Counters.class, id3);
  Assert.assertNull(counters);
  em.close();
}

代码示例来源:origin: Impetus/Kundera

private void findByNameAndAgeWithOrClause()
{
  EntityManager em;
  String query;
  Query q;
  List<StudentHBaseDate> students;
  int count;
  em = emf.createEntityManager();
  query = "Select s From StudentHBaseDate s where s.name = Kuldeep and s.age > " + getPartialValue(short.class);
  q = em.createQuery(query);
  students = q.getResultList();
  Assert.assertNotNull(students);
  Assert.assertEquals(1, students.size());
  count = 0;
  for (StudentHBaseDate student : students)
  {
    Assert.assertEquals(getMaxValue(Date.class), student.getId());
    Assert.assertEquals(getMaxValue(short.class), student.getAge());
    Assert.assertEquals("Kuldeep", student.getName());
    count++;
  }
  Assert.assertEquals(1, count);
  em.close();
}

代码示例来源:origin: spring-projects/spring-framework

@Test
@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());
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
@TestForIssue(jiraKey = "HHH-12138")
public void testNamedNativeQueryStoredProcedureRefCursor() {
  EntityManager entityManager = createEntityManager();
  entityManager.getTransaction().begin();
  try {
    List<Object[]> postAndComments = entityManager
        .createNamedQuery(
            "fn_person_and_phones_hana" )
        .setParameter( 1, 1L )
        .getResultList();
    Object[] postAndComment = postAndComments.get( 0 );
    Person person = (Person) postAndComment[0];
    Phone phone = (Phone) postAndComment[1];
    assertEquals( 2, postAndComments.size() );
  }
  finally {
    entityManager.getTransaction().rollback();
    entityManager.close();
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void deferredQueryWithSingleResult() {
  EntityManagerFactory emf = mock(EntityManagerFactory.class);
  EntityManager targetEm = mock(EntityManager.class);
  Query query = mock(Query.class);
  given(emf.createEntityManager()).willReturn(targetEm);
  given(targetEm.createQuery("x")).willReturn(query);
  given(targetEm.isOpen()).willReturn(true);
  EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
  em.createQuery("x").getSingleResult();
  verify(query).getSingleResult();
  verify(targetEm).close();
}

代码示例来源:origin: kiegroup/jbpm

protected <R> R call(Function<EntityManager, R> function) {
  
  boolean transactionOwner = false;    
  try {
    transactionOwner = txm.begin();
    EntityManager em = emf.createEntityManager();
    R result = function.apply(em);
    txm.commit( transactionOwner );
    em.close();
    return result;
  } catch (Exception e) {
    txm.rollback(transactionOwner);
    throw new RuntimeException( "Exception when persisting error information", e);
  }       
}

代码示例来源:origin: Impetus/Kundera

public void testFindById(boolean useSameEm)
{
  EntityManager em = emf.createEntityManager();
  StudentHBaseCalendar studentMax = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));
  Assert.assertNotNull(studentMax);
  Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());
  Assert.assertEquals(getMaxValue(String.class), studentMax.getName());
  em.close();
}

代码示例来源:origin: spring-projects/spring-framework

@Test
@SuppressWarnings("unchecked")
public void testEntityManagerProxyIsProxy() {
  EntityManager em = createContainerManagedEntityManager();
  assertTrue(Proxy.isProxyClass(em.getClass()));
  Query q = em.createQuery("select p from Person as p");
  List<Person> people = q.getResultList();
  assertTrue(people.isEmpty());
  assertTrue("Should be open to start with", em.isOpen());
  try {
    em.close();
    fail("Close should not work on container managed EM");
  }
  catch (IllegalStateException ex) {
    // OK
  }
  assertTrue(em.isOpen());
}

代码示例来源:origin: Impetus/Kundera

private void findByNameAndAgeWithOrClause()
{
  EntityManager em;
  String query;
  Query q;
  List<StudentMongoShortWrapper> students;
  int count;
  em = emf.createEntityManager();
  query = "Select s From StudentMongoShortWrapper s where s.name = Kuldeep and s.age > " + getMinValue(short.class);
  q = em.createQuery(query);
  students = q.getResultList();
  Assert.assertNotNull(students);
  Assert.assertEquals(1, students.size());
  count = 0;
  for (StudentMongoShortWrapper student : students)
  {
    Assert.assertEquals(getMaxValue(Short.class), student.getId());
    Assert.assertEquals(getMaxValue(short.class), student.getAge());
    Assert.assertEquals("Kuldeep", student.getName());
    count++;
  }
  Assert.assertEquals(1, count);
  em.close();
}

代码示例来源:origin: kiegroup/jbpm

@Test
public void testCreateCorrelation() throws Exception {
  EntityManagerFactory emf = (EntityManagerFactory) context.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
  EntityManager em = emf.createEntityManager();
  Query query = em.createNamedQuery("GetProcessInstanceIdByCorrelation");
  query.setParameter("ckey", "test123");        
  
  List<Long> processInstances = query.getResultList();
  em.close();
  assertNotNull(processInstances);
  assertEquals(1, processInstances.size());
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
  @TestForIssue(jiraKey = "HHH-7780")
  public void testEnumRepresentation() {
    EntityManager entityManager = getEntityManager();
    List<Object> enums1 = entityManager.createNativeQuery(
        "SELECT enums1 FROM EnumSetEntity_enums1_AUD ORDER BY REV ASC"
    ).getResultList();
    List<Object> enums2 = entityManager.createNativeQuery(
        "SELECT enums2 FROM EnumSetEntity_enums2_AUD ORDER BY REV ASC"
    ).getResultList();
    entityManager.close();

    Assert.assertEquals( Arrays.asList( "X", "Y", "X" ), enums1 );

    Assert.assertEquals( 1, enums2.size() );
    Object enum2 = enums2.get( 0 );
    // Compare the Strings to account for, as an example, Oracle returning a BigDecimal instead of an int.
    Assert.assertEquals( "0", enum2.toString() );
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void deferredQueryWithUpdate() {
  EntityManagerFactory emf = mock(EntityManagerFactory.class);
  EntityManager targetEm = mock(EntityManager.class);
  Query query = mock(Query.class);
  given(emf.createEntityManager()).willReturn(targetEm);
  given(targetEm.createQuery("x")).willReturn(query);
  given(targetEm.isOpen()).willReturn(true);
  EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
  em.createQuery("x").executeUpdate();
  verify(query).executeUpdate();
  verify(targetEm).close();
}

相关文章