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;
}
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();
}
}
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);
}
}
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");
});
}
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[]
}
Aggregations