@Override public Spell findByName(String name) { Transaction tx = null; Spell result = null; try (Session session = getSessionFactory().openSession()) { tx = session.beginTransaction(); Criteria criteria = session.createCriteria(persistentClass); criteria.add(Restrictions.eq("name", name)); result = (Spell) criteria.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw e; } return result; } }
@Test public void testDeclarativeMix() throws Exception { Configuration cfg = new Configuration(); cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); SessionFactory sf = cfg.buildSessionFactory(); assertNotNull( sf ); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); Query q = s.createQuery( "from Boat" ); assertEquals( 0, q.list().size() ); q = s.createQuery( "from Plane" ); assertEquals( 0, q.list().size() ); tx.commit(); s.close(); sf.close(); } @Test
statefulSession = sessionFactory.openSession(); return statefulSession.createQuery(queryString);
@Override public void openSession() { log.debug("HibernateContext: Opening Hibernate Session"); if (TransactionSynchronizationManager.hasResource(sessionFactory)) { if (log.isDebugEnabled()) { log.debug("Participating in existing session (" + sessionFactory.hashCode() + ")"); } participate = true; } else { if (log.isDebugEnabled()) { log.debug("Registering session with synchronization manager (" + sessionFactory.hashCode() + ")"); } Session session = sessionFactory.openSession(); session.setFlushMode(FlushMode.MANUAL); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); } }
public Session getThreadSession(boolean create) { Session session = threadSessions.get(); if(session == null && create) { if(logger.isDebugEnabled()) { logger.debug("Creating thread-local session for {}", Thread.currentThread()); } session = sessionFactory.openSession(); session.beginTransaction(); threadSessions.set(session); } return session; }
@Override public void deletePatientPushInfo(String localPatientID) { if (localPatientID == null) { return; } Session session = this.sessionFactory.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); t.begin(); Query query = session.createQuery(HQL_DELETE_ALL_PUSH_HISTRY_FOR_LOCAL_PATIENT); query.setParameter("localId", localPatientID); int numDeleted = query.executeUpdate(); this.logger.debug("Removed all [{}] stored push history records for local patient with ID [{}]", numDeleted, localPatientID); t.commit(); }
logger.debug("About to housekeep by running [" + hibernateQuery + "], where clientId [" + clientId + "], createdDateTime [" + cal.getTime().getTime() Session session = this.sessionFactory.openSession(); try Query query = session.createQuery(hibernateQuery.toString()); query.setParameter(CLIENT_ID, clientId); query.setParameter(CREATED_DATE_TIME, cal.getTime().getTime()); sb.append(hibernateQuery.toString()); sb.append("]."); logger.error(sb.toString() + " " + e.getMessage(), e); throw e;
Session session = null; try { session = getSessionFactory().openSession(); String query0 = "select LOCATION from SAM_MEDIA_T where MEDIAID = :id"; mediaLocation = (String) session.createSQLQuery(query0).setLong("id", mediaId).uniqueResult(); log.debug("****mediaLocation=" + mediaLocation); log.warn(e.getMessage()); } finally { if (session != null) {
Session s = sf.openSession(); s.getTransaction().begin(); EntityWithConvertibleField entity = new EntityWithConvertibleField(); s.close(); s = sf.openSession(); s.beginTransaction(); entity = (EntityWithConvertibleField) s.load( EntityWithConvertibleField.class, entityID ); assertEquals( ConvertibleEnum.VALUE, entity.getConvertibleEnum() ); s.getTransaction().commit(); assertEquals( "'VALUE'", outcome ); s = sf.openSession(); s.beginTransaction(); s.createQuery( "FROM EntityWithConvertibleField e where e.convertibleEnum = org.hibernate.test.converter.AttributeConverterTest$ConvertibleEnum.VALUE" ) .list(); s.getTransaction().commit(); s.close(); s = sf.openSession(); s.beginTransaction(); s.delete( entity ); s.getTransaction().commit();
public static void delete(SessionFactory sessions, Class<?> entityClass, Serializable... ids) { final Session session = sessions.openSession(); Transaction transaction = session.beginTransaction(); for ( Serializable id : ids ) { session.delete( session.load( entityClass, id ) ); } transaction.commit(); session.close(); }
Session session = sessionFactory.openSession(); Query query = session.createQuery(hql); } catch (HibernateException e) { logger.error(e.getMessage(), e); return null; } finally {
@Override public void store(AuditEvent event) { if (ACTION_IGNORED.contains(event.getAction())) { return; } Session session = this.sessionFactory.getSessionFactory().openSession(); try { Transaction t = session.beginTransaction(); t.begin(); session.save(event); t.commit(); } catch (HibernateException ex) { this.logger.error("Failed to save audit event [{}]: {}", event, ex.getMessage(), ex); } finally { session.close(); } }
public void remove(String entityName, Long entityId, String key) { Session session = null; try { session = this.sessionFactory.openSession(); session.delete(HibernatePropertySetDAOUtils.getItem(session, entityName, entityId, key)); session.flush(); } catch (HibernateException e) { throw new PropertyException("Could not remove key '" + key + "': " + e.getMessage()); } finally { try { if (session != null) { session.close(); } } catch (Exception e) { } } } }
@Override protected Session openSession() { if (currentSessionHolder.get() != null) { throw new IllegalStateException("session already open"); } Session session = sessionFactory.openSession(); session.setFlushMode(FlushMode.MANUAL); session.setCacheMode(CacheMode.IGNORE); currentSessionHolder.set(session); log.debug("open new session [{}]", currentSessionHolder.get()); return session; } }
public Session getThreadSession(boolean create) { Session session = threadSessions.get(); if(session == null && create) { if(logger.isDebugEnabled()) { logger.debug("Creating thread-local session for {}", Thread.currentThread()); } session = sessionFactory.openSession(); session.beginTransaction(); threadSessions.set(session); } return session; }
@Test public void testHbmWithSubclassExtends() throws Exception { Configuration cfg = new Configuration(); cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); cfg.addClass( Ferry.class ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); SessionFactory sf = cfg.buildSessionFactory(); assertNotNull( sf ); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); Query q = s.createQuery( "from Ferry" ); assertEquals( 0, q.list().size() ); q = s.createQuery( "from Plane" ); assertEquals( 0, q.list().size() ); tx.commit(); s.close(); sf.close(); } @Test
@Test @SuppressWarnings("unchecked") public void testStatefulClose(){ SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); Query<Foo> scrollableResults = mock(Query.class); HibernateCursorItemReader<Foo> itemReader = new HibernateCursorItemReader<>(); itemReader.setSessionFactory(sessionFactory); itemReader.setQueryString("testQuery"); itemReader.setUseStatelessSession(false); when(sessionFactory.openSession()).thenReturn(session); when(session.createQuery("testQuery")).thenReturn(scrollableResults); when(scrollableResults.setFetchSize(0)).thenReturn(scrollableResults); itemReader.open(new ExecutionContext()); itemReader.close(); }
@Override protected Result check() throws Exception { return timeBoundHealthCheck.check(() -> { try (Session session = sessionFactory.openSession()) { final Transaction txn = session.beginTransaction(); try { session.createNativeQuery(validationQuery).list(); txn.commit(); } catch (Exception e) { if (txn.getStatus().canRollback()) { txn.rollback(); } throw e; } } return Result.healthy(); }); } }
Session session = sf.openSession(); Transaction t = session.beginTransaction(); session.close(); session = sf.openSession(); t = session.beginTransaction(); session.close(); session = sf.openSession(); t = session.beginTransaction(); order = (Orders) session.load(Orders.class, Integer.valueOf(1) ); Assert.assertFalse(Hibernate.isInitialized(order) ); Assert.assertFalse(Hibernate.isInitialized(order.getItemsForOrderId() ) ); order = (Orders) session.createQuery("from " + PACKAGE_NAME + ".Orders").getSingleResult();
/** * Removes the mutations that have a result from the given list of * mutations. * * @param mutations * the list of mutations to be filtered. */ private static void filterMutationsWithResult(List<Mutation> mutations) { if (mutations != null) { // make sure that we have not got any mutations that have already an // result Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List<Mutation> toRemove = new ArrayList<Mutation>(); for (Mutation m : mutations) { session.load(m, m.getId()); if (m.getMutationResult() != null) { logger.debug("Found mutation that already has a mutation result " + m); toRemove.add(m); } } mutations.removeAll(toRemove); tx.commit(); session.close(); } }