Search in sources :

Example 11 with SessionFactory

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

the class AccountDAO method getTotalBalance.

public int getTotalBalance(AccountHolder holder, boolean useRegion) throws Exception {
    List results = (List) withTxSessionApply(useJta, sessionFactory, session -> {
        Query query = session.createQuery("select account.balance from Account as account where account.accountHolder = ?");
        query.setParameter(0, holder);
        if (useRegion) {
            query.setCacheRegion("AccountRegion");
        }
        query.setCacheable(true);
        return query.list();
    });
    int total = 0;
    if (results != null) {
        for (Iterator it = results.iterator(); it.hasNext(); ) {
            total += ((Integer) it.next()).intValue();
            System.out.println("Total = " + total);
        }
    }
    return total;
}
Also used : AccountHolder(org.hibernate.test.cache.infinispan.functional.entities.AccountHolder) List(java.util.List) Iterator(java.util.Iterator) TxUtil.withTxSession(org.hibernate.test.cache.infinispan.util.TxUtil.withTxSession) SessionFactory(org.hibernate.SessionFactory) Query(org.hibernate.Query) Account(org.hibernate.test.cache.infinispan.functional.entities.Account) InfinispanMessageLogger(org.hibernate.cache.infinispan.util.InfinispanMessageLogger) TxUtil.withTxSessionApply(org.hibernate.test.cache.infinispan.util.TxUtil.withTxSessionApply) Query(org.hibernate.Query) Iterator(java.util.Iterator) List(java.util.List)

Example 12 with SessionFactory

use of org.hibernate.SessionFactory in project spring-framework by spring-projects.

the class OpenSessionInterceptor method invoke.

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    SessionFactory sf = getSessionFactory();
    if (!TransactionSynchronizationManager.hasResource(sf)) {
        // New Session to be bound for the current method's scope...
        Session session = openSession();
        try {
            TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
            return invocation.proceed();
        } finally {
            SessionFactoryUtils.closeSession(session);
            TransactionSynchronizationManager.unbindResource(sf);
        }
    } else {
        // Pre-bound Session found -> simply proceed.
        return invocation.proceed();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) SessionHolder(org.springframework.orm.hibernate5.SessionHolder) Session(org.hibernate.Session)

Example 13 with SessionFactory

use of org.hibernate.SessionFactory in project spring-framework by spring-projects.

the class HibernateJpaSessionFactoryBean method getObject.

@Override
public SessionFactory getObject() {
    EntityManagerFactory emf = getEntityManagerFactory();
    Assert.state(emf != null, "EntityManagerFactory must not be null");
    try {
        Method getSessionFactory = emf.getClass().getMethod("getSessionFactory");
        return (SessionFactory) ReflectionUtils.invokeMethod(getSessionFactory, emf);
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException("No compatible Hibernate EntityManagerFactory found: " + ex);
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) EntityManagerFactory(javax.persistence.EntityManagerFactory) Method(java.lang.reflect.Method)

Example 14 with SessionFactory

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

the class PersistenceContextTest method test.

@Test
public void test() {
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        SessionImplementor sessionImplementor = entityManager.unwrap(SessionImplementor.class);
        SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap(SessionFactory.class);
    });
    Long _personId = doInJPA(this::entityManagerFactory, entityManager -> {
        entityManager.createQuery("delete from Book").executeUpdate();
        entityManager.createQuery("delete from Person").executeUpdate();
        Person person = new Person();
        person.setId(1L);
        person.setName("John Doe");
        entityManager.persist(person);
        entityManager.remove(person);
        entityManager.persist(person);
        Long personId = person.getId();
        Book book = new Book();
        book.setAuthor(entityManager.getReference(Person.class, personId));
        return personId;
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        Person person = entityManager.find(Person.class, personId);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        entityManager.createQuery("delete from Book").executeUpdate();
        entityManager.createQuery("delete from Person").executeUpdate();
        Person person = new Person();
        person.setId(1L);
        person.setName("John Doe");
        session.save(person);
        session.delete(person);
        session.save(person);
        Long personId = person.getId();
        Book book = new Book();
        book.setId(1L);
        book.setIsbn("123-456-7890");
        entityManager.persist(book);
        book.setAuthor(session.load(Person.class, personId));
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person person = session.get(Person.class, personId);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person person = session.byId(Person.class).load(personId);
        Optional<Person> optionalPerson = session.byId(Person.class).loadOptional(personId);
        String isbn = "123-456-7890";
        Book book = session.bySimpleNaturalId(Book.class).getReference(isbn);
        assertNotNull(book);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        String isbn = "123-456-7890";
        Book book = session.byNaturalId(Book.class).using("isbn", isbn).load();
        assertNotNull(book);
        Optional<Book> optionalBook = session.byNaturalId(Book.class).using("isbn", isbn).loadOptional();
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        Person person = entityManager.find(Person.class, personId);
        person.setName("John Doe");
        entityManager.flush();
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        Person person = entityManager.find(Person.class, personId);
        entityManager.createQuery("update Person set name = UPPER(name)").executeUpdate();
        entityManager.refresh(person);
        assertEquals("JOHN DOE", person.getName());
    });
    try {
        doInJPA(this::entityManagerFactory, entityManager -> {
            Long personId = _personId;
            try {
                Person person = entityManager.find(Person.class, personId);
                Book book = new Book();
                book.setId(100L);
                book.setTitle("Hibernate User Guide");
                book.setAuthor(person);
                person.getBooks().add(book);
                entityManager.refresh(person);
            } catch (EntityNotFoundException expected) {
                log.info("Beware when cascading the refresh associations to transient entities!");
            }
        });
    } catch (Exception expected) {
    }
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person person = session.byId(Person.class).load(personId);
        person.setName("John Doe");
        entityManager.flush();
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person person = session.byId(Person.class).load(personId);
        session.doWork(connection -> {
            try (Statement statement = connection.createStatement()) {
                statement.executeUpdate("UPDATE Person SET name = UPPER(name)");
            }
        });
        session.refresh(person);
        assertEquals("JOHN DOE", person.getName());
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person person = session.byId(Person.class).load(personId);
        session.clear();
        person.setName("Mr. John Doe");
        session.lock(person, LockMode.NONE);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person person = session.byId(Person.class).load(personId);
        session.clear();
        person.setName("Mr. John Doe");
        session.saveOrUpdate(person);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person personDetachedReference = session.byId(Person.class).load(personId);
        session.clear();
        new MergeVisualizer(session).merge(personDetachedReference);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        Person person = entityManager.find(Person.class, personId);
        entityManager.clear();
        person.setName("Mr. John Doe");
        person = entityManager.merge(person);
        boolean contained = entityManager.contains(person);
        assertTrue(contained);
        PersistenceUnitUtil persistenceUnitUtil = entityManager.getEntityManagerFactory().getPersistenceUnitUtil();
        boolean personInitialized = persistenceUnitUtil.isLoaded(person);
        boolean personBooksInitialized = persistenceUnitUtil.isLoaded(person.getBooks());
        boolean personNameInitialized = persistenceUnitUtil.isLoaded(person, "name");
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        Person person = entityManager.find(Person.class, personId);
        PersistenceUtil persistenceUnitUtil = Persistence.getPersistenceUtil();
        boolean personInitialized = persistenceUnitUtil.isLoaded(person);
        boolean personBooksInitialized = persistenceUnitUtil.isLoaded(person.getBooks());
        boolean personNameInitialized = persistenceUnitUtil.isLoaded(person, "name");
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person person = session.byId(Person.class).load(personId);
        session.clear();
        person.setName("Mr. John Doe");
        person = (Person) session.merge(person);
        boolean contained = session.contains(person);
        assertTrue(contained);
        boolean personInitialized = Hibernate.isInitialized(person);
        boolean personBooksInitialized = Hibernate.isInitialized(person.getBooks());
        boolean personNameInitialized = Hibernate.isPropertyInitialized(person, "name");
    });
}
Also used : SessionFactory(org.hibernate.SessionFactory) Statement(java.sql.Statement) PersistenceUnitUtil(javax.persistence.PersistenceUnitUtil) EntityNotFoundException(javax.persistence.EntityNotFoundException) EntityNotFoundException(javax.persistence.EntityNotFoundException) PersistenceUtil(javax.persistence.PersistenceUtil) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) Session(org.hibernate.Session) Test(org.junit.Test)

Example 15 with SessionFactory

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

the class TransactionsTest method cmt.

@Test
public void cmt() {
    //tag::transactions-api-cmt-example[]
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySetting(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta").build();
    Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(Customer.class).getMetadataBuilder().build();
    SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
    // Note: depending on the JtaPlatform used and some optional settings,
    // the underlying transactions here will be controlled through either
    // the JTA TransactionManager or UserTransaction
    Session session = sessionFactory.openSession();
    try {
        // Since we are in CMT, a JTA transaction would
        // already have been started.  This call essentially
        // no-ops
        session.getTransaction().begin();
        Number customerCount = (Number) session.createQuery("select count(c) from Customer c").uniqueResult();
        // Since we did not start the transaction ( CMT ),
        // we also will not end it.  This call essentially
        // no-ops in terms of transaction handling.
        session.getTransaction().commit();
    } catch (Exception e) {
        // marking the underlying CMT transaction for rollback only).
        if (session.getTransaction().getStatus() == TransactionStatus.ACTIVE || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK) {
            session.getTransaction().rollback();
        }
    // handle the underlying error
    } finally {
        session.close();
        sessionFactory.close();
    }
//end::transactions-api-cmt-example[]
}
Also used : SessionFactory(org.hibernate.SessionFactory) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) Session(org.hibernate.Session) Test(org.junit.Test)

Aggregations

SessionFactory (org.hibernate.SessionFactory)106 Test (org.junit.Test)62 Session (org.hibernate.Session)49 Configuration (org.hibernate.cfg.Configuration)34 Transaction (org.hibernate.Transaction)19 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