Search in sources :

Example 86 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class InterceptorTest method testSessionInterceptor.

@Test
public void testSessionInterceptor() {
    EntityManagerFactory entityManagerFactory = entityManagerFactory();
    Serializable customerId = 1L;
    //tag::events-interceptors-session-scope-example[]
    SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
    Session session = sessionFactory.withOptions().interceptor(new LoggingInterceptor()).openSession();
    session.getTransaction().begin();
    Customer customer = session.get(Customer.class, customerId);
    customer.setName("Mr. John Doe");
    //Entity Customer#1 changed from [John Doe, 0] to [Mr. John Doe, 0]
    session.getTransaction().commit();
    //end::events-interceptors-session-scope-example[]
    session.close();
}
Also used : SessionFactory(org.hibernate.SessionFactory) Serializable(java.io.Serializable) EntityManagerFactory(javax.persistence.EntityManagerFactory) Session(org.hibernate.Session) Test(org.junit.Test)

Example 87 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class InterceptorTest method testSessionFactoryInterceptor.

@Test
public void testSessionFactoryInterceptor() {
    Serializable customerId = 1L;
    //tag::events-interceptors-session-factory-scope-example[]
    SessionFactory sessionFactory = new MetadataSources(new StandardServiceRegistryBuilder().build()).addAnnotatedClass(Customer.class).getMetadataBuilder().build().getSessionFactoryBuilder().applyInterceptor(new LoggingInterceptor()).build();
    //end::events-interceptors-session-factory-scope-example[]
    Session session = sessionFactory.openSession();
    session.getTransaction().begin();
    Customer customer = session.get(Customer.class, customerId);
    customer.setName("Mr. John Doe");
    //Entity Customer#1 changed from [John Doe, 0] to [Mr. John Doe, 0]
    session.getTransaction().commit();
    session.close();
    sessionFactory.close();
}
Also used : SessionFactory(org.hibernate.SessionFactory) Serializable(java.io.Serializable) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) MetadataSources(org.hibernate.boot.MetadataSources) Session(org.hibernate.Session) Test(org.junit.Test)

Example 88 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class BatchTest method withStatelessSession.

private void withStatelessSession() {
    withBatch();
    //tag::batch-stateless-session-example[]
    StatelessSession statelessSession = null;
    Transaction txn = null;
    ScrollableResults scrollableResults = null;
    try {
        SessionFactory sessionFactory = entityManagerFactory().unwrap(SessionFactory.class);
        statelessSession = sessionFactory.openStatelessSession();
        txn = statelessSession.getTransaction();
        txn.begin();
        scrollableResults = statelessSession.createQuery("select p from Person p").scroll(ScrollMode.FORWARD_ONLY);
        while (scrollableResults.next()) {
            Person Person = (Person) scrollableResults.get(0);
            processPerson(Person);
            statelessSession.update(Person);
        }
        txn.commit();
    } catch (RuntimeException e) {
        if (txn != null && txn.getStatus() == TransactionStatus.ACTIVE)
            txn.rollback();
        throw e;
    } finally {
        if (scrollableResults != null) {
            scrollableResults.close();
        }
        if (statelessSession != null) {
            statelessSession.close();
        }
    }
//end::batch-stateless-session-example[]
}
Also used : SessionFactory(org.hibernate.SessionFactory) StatelessSession(org.hibernate.StatelessSession) Transaction(org.hibernate.Transaction) EntityTransaction(javax.persistence.EntityTransaction) ScrollableResults(org.hibernate.ScrollableResults) Person(org.hibernate.userguide.model.Person)

Example 89 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class StoredProcedureResultSetMappingTest method testPartialResults.

@Test
public void testPartialResults() {
    Configuration cfg = new Configuration().addAnnotatedClass(Employee.class).setProperty(AvailableSettings.HBM2DDL_AUTO, "create-drop");
    cfg.addAuxiliaryDatabaseObject(new ProcedureDefinition());
    SessionFactory sf = cfg.buildSessionFactory();
    try {
        Session session = sf.openSession();
        session.beginTransaction();
        ProcedureCall call = session.createStoredProcedureCall("allEmployeeNames", "id-fname-lname");
        ProcedureOutputs outputs = call.getOutputs();
        ResultSetOutput output = assertTyping(ResultSetOutput.class, outputs.getCurrent());
        assertEquals(3, output.getResultList().size());
        assertTyping(Employee.class, output.getResultList().get(0));
        session.getTransaction().commit();
        session.close();
    } finally {
        sf.close();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) ResultSetOutput(org.hibernate.result.ResultSetOutput) ProcedureCall(org.hibernate.procedure.ProcedureCall) Configuration(org.hibernate.cfg.Configuration) ProcedureOutputs(org.hibernate.procedure.ProcedureOutputs) Session(org.hibernate.Session) Test(org.junit.Test)

Example 90 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class StatsTest method testQueryStatGathering.

//
//	@Test
//	@SuppressWarnings( {"UnusedAssignment"})
//	public void testCollectionFetchVsLoad() throws Exception {
//		SessionFactory sf = buildBaseConfiguration()
//				.setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" )
//				.buildSessionFactory();
//
//		Session s = sf.openSession();
//		Transaction tx = s.beginTransaction();
//		Continent europe = fillDb(s);
//		tx.commit();
//		s.close();
//
//		s = sf.openSession();
//		tx = s.beginTransaction();
//		assertEquals(0, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals(0,  sf.getStatistics().getCollectionFetchCount() );
//		Continent europe2 = (Continent) s.get( Continent.class, europe.getId() );
//		assertEquals("Lazy true: no collection should be loaded", 0, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
//		europe2.getCountries().size();
//		assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals("Explicit fetch of the collection state", 1, sf.getStatistics().getCollectionFetchCount() );
//		tx.commit();
//		s.close();
//
//		sf.getStatistics().clear();
//
//		s = sf.openSession();
//		tx = s.beginTransaction();
//		europe = fillDb(s);
//		tx.commit();
//		s.clear();
//		tx = s.beginTransaction();
//		assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
//		europe2 = (Continent) s.createQuery(
//				"from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
//			).uniqueResult();
//		assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals( "collection should be loaded in the same query as its parent", 0, sf.getStatistics().getCollectionFetchCount() );
//		tx.commit();
//		s.close();
//
//		// open a new SF
//		sf.close();
//		Configuration cfg = buildBaseConfiguration().setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
//		cfg.buildMappings();
//		Collection coll = cfg.getCollectionMapping(Continent.class.getName() + ".countries");
//		coll.setFetchMode(FetchMode.JOIN);
//		coll.setLazy(false);
//		sf = cfg.buildSessionFactory();
//
//		s = sf.openSession();
//		tx = s.beginTransaction();
//		europe = fillDb(s);
//		tx.commit();
//		s.close();
//
//		s = sf.openSession();
//		tx = s.beginTransaction();
//		assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
//		europe2 = (Continent) s.get( Continent.class, europe.getId() );
//		assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, sf.getStatistics().getCollectionFetchCount() );
//		tx.commit();
//		s.close();
//		sf.close();
//
//		// open yet another SF
//		sf.close();
//		cfg = buildBaseConfiguration().setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
//		cfg.buildMappings();
//		coll = cfg.getCollectionMapping( Continent.class.getName() + ".countries" );
//		coll.setFetchMode(FetchMode.SELECT);
//		coll.setLazy(false);
//		sf = cfg.buildSessionFactory();
//
//		s = sf.openSession();
//		tx = s.beginTransaction();
//		europe = fillDb(s);
//		tx.commit();
//		s.close();
//
//		s = sf.openSession();
//		tx = s.beginTransaction();
//		assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
//		europe2 = (Continent) s.get( Continent.class, europe.getId() );
//		assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
//		assertEquals( "Should do explicit collection load, not part of the first one", 1, sf.getStatistics().getCollectionFetchCount() );
//		for ( Object o : europe2.getCountries() ) {
//			s.delete( o );
//		}
//		cleanDb( s );
//		tx.commit();
//		s.close();
//
//		sf.close();
//	}
@Test
public void testQueryStatGathering() {
    SessionFactory sf = buildBaseConfiguration().setProperty(AvailableSettings.HBM2DDL_AUTO, "create-drop").buildSessionFactory();
    Session s = sf.openSession();
    Transaction tx = s.beginTransaction();
    fillDb(s);
    tx.commit();
    s.close();
    s = sf.openSession();
    tx = s.beginTransaction();
    final String continents = "from Continent";
    int results = s.createQuery(continents).list().size();
    QueryStatistics continentStats = sf.getStatistics().getQueryStatistics(continents);
    assertNotNull("stats were null", continentStats);
    assertEquals("unexpected execution count", 1, continentStats.getExecutionCount());
    assertEquals("unexpected row count", results, continentStats.getExecutionRowCount());
    long maxTime = continentStats.getExecutionMaxTime();
    assertEquals(maxTime, sf.getStatistics().getQueryExecutionMaxTime());
    //		assertEquals( continents, stats.getQueryExecutionMaxTimeQueryString() );
    Iterator itr = s.createQuery(continents).iterate();
    // iterate() should increment the execution count
    assertEquals("unexpected execution count", 2, continentStats.getExecutionCount());
    // but should not effect the cumulative row count
    assertEquals("unexpected row count", results, continentStats.getExecutionRowCount());
    Hibernate.close(itr);
    ScrollableResults scrollableResults = s.createQuery(continents).scroll();
    // same deal with scroll()...
    assertEquals("unexpected execution count", 3, continentStats.getExecutionCount());
    assertEquals("unexpected row count", results, continentStats.getExecutionRowCount());
    // if data is not read beforeQuery closing the ResultSet
    while (scrollableResults.next()) {
    // do nothing
    }
    scrollableResults.close();
    tx.commit();
    s.close();
    // explicitly check that statistics for "split queries" get collected
    // under the original query
    sf.getStatistics().clear();
    s = sf.openSession();
    tx = s.beginTransaction();
    final String localities = "from Locality";
    results = s.createQuery(localities).list().size();
    QueryStatistics localityStats = sf.getStatistics().getQueryStatistics(localities);
    assertNotNull("stats were null", localityStats);
    // ...one for each split query
    assertEquals("unexpected execution count", 2, localityStats.getExecutionCount());
    assertEquals("unexpected row count", results, localityStats.getExecutionRowCount());
    maxTime = localityStats.getExecutionMaxTime();
    assertEquals(maxTime, sf.getStatistics().getQueryExecutionMaxTime());
    //		assertEquals( localities, stats.getQueryExecutionMaxTimeQueryString() );
    tx.commit();
    s.close();
    assertFalse(s.isOpen());
    // native sql queries
    sf.getStatistics().clear();
    s = sf.openSession();
    tx = s.beginTransaction();
    final String sql = "select id, name from Country";
    results = s.createSQLQuery(sql).addEntity(Country.class).list().size();
    QueryStatistics sqlStats = sf.getStatistics().getQueryStatistics(sql);
    assertNotNull("sql stats were null", sqlStats);
    assertEquals("unexpected execution count", 1, sqlStats.getExecutionCount());
    assertEquals("unexpected row count", results, sqlStats.getExecutionRowCount());
    maxTime = sqlStats.getExecutionMaxTime();
    assertEquals(maxTime, sf.getStatistics().getQueryExecutionMaxTime());
    //		assertEquals( sql, stats.getQueryExecutionMaxTimeQueryString() );
    tx.commit();
    s.close();
    s = sf.openSession();
    tx = s.beginTransaction();
    cleanDb(s);
    tx.commit();
    s.close();
    sf.close();
}
Also used : SessionFactory(org.hibernate.SessionFactory) Transaction(org.hibernate.Transaction) QueryStatistics(org.hibernate.stat.QueryStatistics) Iterator(java.util.Iterator) ScrollableResults(org.hibernate.ScrollableResults) Session(org.hibernate.Session) Test(org.junit.Test)

Aggregations

SessionFactory (org.hibernate.SessionFactory)108 Test (org.junit.Test)62 Session (org.hibernate.Session)50 Configuration (org.hibernate.cfg.Configuration)35 Transaction (org.hibernate.Transaction)20 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)19 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)13 MetadataSources (org.hibernate.boot.MetadataSources)11 HibernateEntityManagerFactory (org.hibernate.jpa.HibernateEntityManagerFactory)9 TestForIssue (org.hibernate.testing.TestForIssue)9 Properties (java.util.Properties)8 Query (org.hibernate.Query)8 Metadata (org.hibernate.boot.Metadata)8 ArrayList (java.util.ArrayList)7 InfinispanRegionFactory (org.hibernate.cache.infinispan.InfinispanRegionFactory)7 List (java.util.List)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 TimeUnit (java.util.concurrent.TimeUnit)5 AnnotationException (org.hibernate.AnnotationException)5 Collections (java.util.Collections)4