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

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

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

EntityManager.clear介绍

[英]Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.
[中]清除持久性上下文,使所有托管实体分离。对尚未刷新到数据库的实体所做的更改将不会持久化。

代码示例

代码示例来源:origin: stackoverflow.com

EntityManager em = ...;
EntityTransaction tx = em.getTransaction();
tx.begin();

for ( int i=0; i<100000; i++ ) {
  Customer customer = new Customer(.....);
  em.persist(customer);
  if ( i % 20 == 0 ) { //20, same as the JDBC batch size
    //flush a batch of inserts and release memory:
    em.flush();
    em.clear();
  }
}

tx.commit();
session.close();

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

@Test
public void testTransactionCommitWithSharedEntityManagerAndPropagationSupports() {
  given(manager.isOpen()).willReturn(true);
  tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
  tt.execute(status -> {
    bean.sharedEntityManager.clear();
    return null;
  });
  verify(manager).clear();
  verify(manager).close();
}

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

@Test
@Priority(10)
public void initData() {
  final EntityManager em = getEntityManager();
  final SetOwningEntity setOwningEntity = new SetOwningEntity( 1, "parent" );
  final SetOwnedEntity setOwnedEntity = new SetOwnedEntity( 2, "child" );
  // Revision 1: Initial persist
  em.getTransaction().begin();
  em.persist( setOwningEntity );
  em.persist( setOwnedEntity );
  em.getTransaction().commit();
  em.clear();
  ing_id = setOwningEntity.getId();
  ed_id = setOwnedEntity.getId();
}

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

@Test
@Priority(10)
public void initData() {
  EntityManager entityManager = getOrCreateEntityManager();
  try {
    // Revision 1
    SimpleEntity se = new SimpleEntity();
    se.setData( "data" );
    entityManager.getTransaction().begin();
    entityManager.persist( se );
    entityManager.getTransaction().commit();
    entityManager.clear();
    entityId = se.getId();
    // Revision 2
    entityManager.getTransaction().begin();
    se = entityManager.find( SimpleEntity.class, se.getId() );
    se.setData( "data2" );
    entityManager.merge( se );
    entityManager.getTransaction().commit();
    // Revision 3
    entityManager.getTransaction().begin();
    se = entityManager.find( SimpleEntity.class, se.getId() );
    entityManager.remove( se );
    entityManager.getTransaction().commit();
  }
  finally {
    entityManager.close();
  }
}

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

@Test
@Priority(5)
public void testMultipleAddAndRemove() {
  SetOwningEntity owningEntity = getEntityManager().find( SetOwningEntity.class, ing_id );
  SetOwnedEntity ownedEntity = getEntityManager().find( SetOwnedEntity.class, ed_id );
  em.clear();
  owningEntity = getEntityManager().find( SetOwningEntity.class, ing_id );
  ownedEntity = getEntityManager().find( SetOwnedEntity.class, ed_id );
  em.clear();
  em.clear();
  em.clear();

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

@Test
@RequiresDialect(H2Dialect.class)
@RequiresDialect(PostgreSQL81Dialect.class)
@RequiresDialect(MySQL5Dialect.class)
public void test_hql_group_by_example_4() {
  doInJPA( this::entityManagerFactory, entityManager -> {
    Call call11 = new Call();
    call11.setDuration( 10 );
    call11.setTimestamp( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ).toInstant( ZoneOffset.UTC ) ) );
    Phone phone = entityManager.createQuery( "select p from Phone p where p.calls is empty ", Phone.class).getResultList().get( 0 );
    phone.addCall(call11);
    entityManager.flush();
    entityManager.clear();
    List<Object[]> personTotalCallDurations = entityManager.createQuery(
      "select p, sum( c.duration ) " +
      "from Call c " +
      "join c.phone p " +
      "group by p", Object[].class )
    .getResultList();
    assertEquals(2, personTotalCallDurations.size());
  });
}

代码示例来源:origin: AxonFramework/AxonFramework

@SuppressWarnings({"unchecked"})
@Test
public void testStoreAndLoadNewAggregate() throws Exception {
  UnitOfWork<?> uow = startAndGetUnitOfWork();
  String originalId = repository.newInstance(() -> new JpaAggregate("Hello")).invoke(JpaAggregate::getIdentifier);
  uow.commit();
  entityManager.flush();
  entityManager.clear();
  List<JpaAggregate> results = entityManager.createQuery("SELECT a FROM JpaAggregate a").getResultList();
  assertEquals(1, results.size());
  JpaAggregate aggregate = results.get(0);
  assertEquals(originalId, aggregate.getIdentifier());
  uow = startAndGetUnitOfWork();
  Aggregate<JpaAggregate> storedAggregate = repository.load(originalId);
  uow.commit();
  assertEquals(storedAggregate.identifierAsString(), originalId);
  assertTrue(capturedEvents.isEmpty());
}

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

@Override
public List<UserCassandra> getAllUsers()
{
  em.clear();
  Query q = em.createQuery("select u from UserCassandra u");
  List<UserCassandra> users = q.getResultList();
  return users;
}

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

/**
 * Test insert.
 */
private void testInsert()
{
  em.persist(p1);
  em.persist(p2);
  em.clear();
  PersonEmbed person1 = em.find(PersonEmbed.class, 1);
  PersonEmbed person2 = em.find(PersonEmbed.class, 2);
  assertPerson(p1, person1);
  assertPerson(p2, person2);
}

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

@Test
@Priority(10)
public void initData() {
  EntityManager entityManager = getEntityManager();
  try {
    // Revision 1 - insertion
    Professor professor = new Professor();
    Student student = new Student();
    professor.getStudents().add( student );
    student.getProfessors().add( professor );
    entityManager.getTransaction().begin();
    entityManager.persist( professor );
    entityManager.persist( student );
    entityManager.getTransaction().commit();
    entityManager.clear();
    // Revision 2 - deletion
    entityManager.getTransaction().begin();
    professor = entityManager.find( Professor.class, professor.getId() );
    student = entityManager.find( Student.class, student.getId() );
    entityManager.remove( professor );
    entityManager.remove( student );
    // the issue is student.getProfessors() throws a LazyInitializationException.
    entityManager.getTransaction().commit();
  }
  finally {
    entityManager.close();
  }
}

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

@Test
  public void testBasicPersistAndAuditFetch() throws Exception {
    EntityManager entityManager = getOrCreateEntityManager();
    try {
      StrTestEntity e = new StrTestEntity( "Acme" );
      entityManager.getTransaction().begin();
      entityManager.persist( e );
      entityManager.getTransaction().commit();
      entityManager.clear();

      StrTestEntity rev1 = getAuditReader().find ( StrTestEntity.class, e.getId(), 1 );
      assertEquals( e, rev1 );
    }
    catch ( Exception e ) {
      if ( entityManager.getTransaction().isActive() ) {
        entityManager.getTransaction().rollback();
      }
      throw e;
    }
    finally {
      entityManager.close();
    }
  }
}

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

@Test
public void testTransactionCommitWithSharedEntityManagerUnsynchronizedAndPropagationSupports() {
  given(manager.isOpen()).willReturn(true);
  tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
  tt.execute(status -> {
    bean.sharedEntityManagerUnsynchronized.clear();
    return null;
  });
  verify(manager).clear();
  verify(manager).close();
}

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

/************* Queries on Professional Details for all data types *************/
@Override
public List<UserCassandra> findUserByProfessionId(long professionId)
{
  em.clear();
  Query q = em
      .createQuery("select u from UserCassandra u where u.professionalDetail.professionId =:professionId");
  q.setParameter("professionId", professionId);
  List<UserCassandra> users = q.getResultList();
  return users;
}

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

public void testPersist()
{
  Person person1 = getPerson("1", "dev", 22, 30000.5);
  em.persist(person1);
  em.clear();
  Person p = em.find(Person.class, "1");
  validatePerson1(p);
}

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

private void withBatch() {
  int entityCount = 100;
  //tag::batch-session-batch-insert-example[]
  EntityManager entityManager = null;
  EntityTransaction txn = null;
  try {
    entityManager = entityManagerFactory().createEntityManager();
    txn = entityManager.getTransaction();
    txn.begin();
    int batchSize = 25;
    for ( int i = 0; i < entityCount; i++ ) {
      if ( i > 0 && i % batchSize == 0 ) {
        //flush a batch of inserts and release memory
        entityManager.flush();
        entityManager.clear();
      }
      Person Person = new Person( String.format( "Person %d", i ) );
      entityManager.persist( Person );
    }
    txn.commit();
  } catch (RuntimeException e) {
    if ( txn != null && txn.isActive()) txn.rollback();
      throw e;
  } finally {
    if (entityManager != null) {
      entityManager.close();
    }
  }
  //end::batch-session-batch-insert-example[]
}

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

@Test
@Priority(10)
public void initData() {
  em.persist( set1 );
  em.persist( set2 );
  em.clear();
  g1.setGreetingSet( em.getReference( GreetingSetPO.class, set1_id ) );
  em.persist( g1 );
  g1_id = g1.getId();
  em.clear();
  g1 = em.find( GreetingPO.class, g1_id );

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

@Test
public void testLazyLoading() {
  try {
    Person tony = new Person();
    tony.setFirstName("Tony");
    tony.setLastName("Blair");
    tony.setDriversLicense(new DriversLicense("8439DK"));
    sharedEntityManager.persist(tony);
    setComplete();
    endTransaction();
    startNewTransaction();
    sharedEntityManager.clear();
    Person newTony = entityManagerFactory.createEntityManager().getReference(Person.class, tony.getId());
    assertNotSame(newTony, tony);
    endTransaction();
    assertNotNull(newTony.getDriversLicense());
    newTony.getDriversLicense().getSerialNumber();
  }
  finally {
    deleteFromTables("person", "drivers_license");
  }
}

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

@Test
public void testTransactionRollbackWithPrebound() {
  given(manager.getTransaction()).willReturn(tx);
  given(tx.isActive()).willReturn(true);
  assertTrue(!TransactionSynchronizationManager.hasResource(factory));
  assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
  TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
  try {
    tt.execute(new TransactionCallback() {
      @Override
      public Object doInTransaction(TransactionStatus status) {
        assertTrue(TransactionSynchronizationManager.hasResource(factory));
        assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
        EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
        status.setRollbackOnly();
        return null;
      }
    });
    assertTrue(TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
  }
  finally {
    TransactionSynchronizationManager.unbindResource(factory);
  }
  verify(tx).begin();
  verify(tx).rollback();
  verify(manager).clear();
}

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

@Override
public List<UserCassandra> findUserByDepartment(String departmentName)
{
  em.clear();
  Query q = em
      .createQuery("select u from UserCassandra u where u.professionalDetail.departmentName =:departmentName");
  q.setParameter("departmentName", departmentName);
  List<UserCassandra> users = q.getResultList();
  return users;
}

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

/**
 * Test insert.
 */
private void testInsert()
{
  byte[] profilePic = createBinaryData("src/test/resources/pic.jpg", 20);
  GFSUser user = prepareUserObject(1, "Dev", profilePic);
  em.persist(user);
  em.clear();
  GFSUser u = em.find(GFSUser.class, 1);
  Assert.assertEquals("Dev", u.getName());
  Assert.assertEquals(profilePic.length, u.getProfilePic().length);
}

相关文章