/** * Associates the given session with the current thread of execution. * * @param session The session to bind. */ public static void bind(org.hibernate.Session session) { final SessionFactory factory = session.getSessionFactory(); doBind( session, factory ); }
@Override @SuppressWarnings({"unchecked", "RedundantCast"}) default <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) { return (List) getSessionFactory().findEntityGraphsByType( entityClass ); }
/** * Binds the given session to the current context for its session factory. * * @param session The session to be bound. * @return Any previously bound session (should be null in most cases). */ public static Session bind(Session session) { return sessionMap( true ).put( session.getSessionFactory(), session ); }
@Override public SessionFactory getSessionFactory(HibernateEntityManager entityManager) { return entityManager.getSession().getSessionFactory(); }
@Override public Field getIdField(Class<?> clazz, Session session) { clazz = getNonProxyImplementationClassIfNecessary(clazz); ClassMetadata metadata = session.getSessionFactory().getClassMetadata(clazz); Field idField = ReflectionUtils.findField(clazz, metadata.getIdentifierPropertyName()); idField.setAccessible(true); return idField; } }
@Override public void execute() throws Throwable { Class<?>[] entitiesFromCeiling = daoHelper.getAllPolymorphicEntitiesFromCeiling(clazz[0], em.unwrap(Session.class).getSessionFactory(), true, true); if (entitiesFromCeiling == null || entitiesFromCeiling.length < 1) { clazz[0] = DynamicDaoHelperImpl.getNonProxyImplementationClassIfNecessary(clazz[0]); entitiesFromCeiling = daoHelper.getAllPolymorphicEntitiesFromCeiling(clazz[0], em.unwrap(Session.class).getSessionFactory(), true, true); } if (entitiesFromCeiling == null || entitiesFromCeiling.length < 1) { throw new IllegalArgumentException(String.format("Unable to find ceiling implementation for the requested class name (%s)", className)); } clazz[0] = entitiesFromCeiling[entitiesFromCeiling.length - 1]; } }, RuntimeException.class, !TransactionUtils.isTransactionalEntityManager(em));
public Dialect getHibernateDialect(EntityManager em) { SessionFactoryImplementor factory = (SessionFactoryImplementor) em.unwrap(Session.class).getSessionFactory(); return factory.getDialect(); }
@Override public Field getIdField(Class<?> clazz, EntityManager em) { clazz = getNonProxyImplementationClassIfNecessary(clazz); ClassMetadata metadata = em.unwrap(Session.class).getSessionFactory().getClassMetadata(clazz); Field idField = ReflectionUtils.findField(clazz, metadata.getIdentifierPropertyName()); idField.setAccessible(true); return idField; }
@Override public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) { entityClass = getNonProxyImplementationClassIfNecessary(entityClass); Map<String, Object> response = new HashMap<>(); SessionFactory sessionFactory = entityManager.getSession().getSessionFactory(); ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass); if (metadata == null) { return null; } String idProperty = metadata.getIdentifierPropertyName(); response.put("name", idProperty); Type idType = metadata.getIdentifierType(); response.put("type", idType); return response; }
/** * Create an audit reader associated with an open session. * * @param session An open session. * * @return An audit reader associated with the given sesison. It shouldn't be used * after the session is closed. * * @throws AuditException When the given required listeners aren't installed. */ public static AuditReader get(Session session) throws AuditException { SessionImplementor sessionImpl; if ( !(session instanceof SessionImplementor) ) { sessionImpl = (SessionImplementor) session.getSessionFactory().getCurrentSession(); } else { sessionImpl = (SessionImplementor) session; } final ServiceRegistry serviceRegistry = sessionImpl.getFactory().getServiceRegistry(); final EnversService enversService = serviceRegistry.getService( EnversService.class ); return new AuditReaderImpl( enversService, session, sessionImpl ); }
protected String getClassNameForSection(String sectionKey) { try { AdminSection section = adminNavigationService.findAdminSectionByURI("/" + sectionKey); String className = (section == null) ? sectionKey : section.getCeilingEntity(); if (className == null) { throw new RuntimeException("Could not determine the class related to the following Section: " + section.getName()); } SessionFactory sessionFactory = getEntityManager(className).unwrap(Session.class).getSessionFactory(); Class<?>[] entities = dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(Class.forName(className), sessionFactory, true, true); return entities[entities.length - 1].getName(); } catch (ClassNotFoundException e) { throw ExceptionHelper.refineException(RuntimeException.class, RuntimeException.class, e); } }
@Override public Class<?> getCeilingImplClassFromEntityManagers(String className) { Class<?> beanIdClass = getClassForName(className); for (EntityManager em : entityManagers) { Class<?>[] entitiesFromCeiling = daoHelper.getAllPolymorphicEntitiesFromCeiling(beanIdClass, em.unwrap(Session.class).getSessionFactory(), true, true); if (ArrayUtils.isNotEmpty(entitiesFromCeiling)) { return entitiesFromCeiling[entitiesFromCeiling.length - 1]; } } return null; }
@Test @TestForIssue( jiraKey = "HHH-7278" ) public void testInsertedNaturalIdCachedAfterTransactionSuccess() { Session session = openSession(); session.getSessionFactory().getStatistics().clear(); session.beginTransaction(); Another it = new Another( "it"); session.save( it ); session.flush(); session.getTransaction().commit(); session.close(); session = openSession(); session.beginTransaction(); it = (Another) session.bySimpleNaturalId(Another.class).load("it"); assertNotNull(it); session.delete(it); session.getTransaction().commit(); assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount()); }
@Test @TestForIssue( jiraKey = "HHH-7309" ) public void testInsertUpdateEntity_NaturalIdCachedAfterTransactionSuccess() { Session session = openSession(); session.getSessionFactory().getStatistics().clear(); session.beginTransaction(); Another it = new Another( "it"); session.save( it ); // schedules an InsertAction it.setSurname("1234"); // schedules an UpdateAction, without bug-fix // this will re-cache natural-id with identical key and at same time invalidate it session.flush(); session.getTransaction().commit(); session.close(); session = openSession(); session.beginTransaction(); it = (Another) session.bySimpleNaturalId(Another.class).load("it"); assertNotNull(it); session.delete(it); session.getTransaction().commit(); assertEquals("In a strict access strategy we would excpect a hit here", 1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount()); }
@Test @TestForIssue( jiraKey = "HHH-7278" ) public void testInsertedNaturalIdNotCachedAfterTransactionFailure() { Session session = openSession(); session.getSessionFactory().getStatistics().clear(); session.beginTransaction(); Another it = new Another( "it"); session.save( it ); session.flush(); session.getTransaction().rollback(); session.close(); session = openSession(); session.beginTransaction(); it = (Another) session.bySimpleNaturalId(Another.class).load("it"); assertNull(it); assertEquals(0, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount()); }
session.close(); session.getSessionFactory().getStatistics().clear(); session.close(); assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
private void checkSQLOrderBy(Session session, String entityName, String propertyName, String order) { String roleName = entityName + "." + propertyName; String alias = "alias1"; BasicCollectionPersister collectionPersister = (BasicCollectionPersister) session.getSessionFactory().getCollectionMetadata( roleName ); Assert.assertTrue( collectionPersister.hasOrdering() ); Assert.assertEquals( alias + "." + propertyName + " " + order, collectionPersister.getSQLOrderByString( alias ) ); }
@Test @SuppressWarnings("unchecked") public void testMapXMLSupport() throws Exception { Session s = openSession(); SessionFactory sf = s.getSessionFactory(); Transaction tx = s.beginTransaction(); // Verify that we can persist an object with a couple Map mappings VicePresident vpSales = new VicePresident(); vpSales.name = "Dwight"; Company company = new Company(); company.conferenceRoomExtensions.put( "8932", "x1234" ); company.organization.put( "sales", vpSales ); s.persist( company ); s.flush(); s.clear(); // For the element-collection, check that the orm.xml entries are honored. // This includes: map-key-column/column/collection-table/join-column BasicCollectionPersister confRoomMeta = (BasicCollectionPersister) sf.getCollectionMetadata( Company.class.getName() + ".conferenceRoomExtensions" ); assertEquals( "company_id", confRoomMeta.getKeyColumnNames()[0] ); assertEquals( "phone_extension", confRoomMeta.getElementColumnNames()[0] ); assertEquals( "room_number", confRoomMeta.getIndexColumnNames()[0] ); assertEquals( "phone_extension_lookup", confRoomMeta.getTableName() ); tx.rollback(); s.close(); }
@Test public void testFiltersAreApplied() { doInHibernate( this::sessionFactory, session -> { session.enableFilter( "ID" ).setParameter( "id", 3L ); List result = session.createQuery( "from Customer order by id" ).list(); assertFalse( result.isEmpty() ); Customer customer = (Customer) result.get( 0 ); assertSame( customer.getCustomerId(), 3L ); assertSame( customer.getOrders().size(), 2 ); SessionStatistics statistics = session.getStatistics(); assertSame( statistics.getEntityCount(), 9 ); Statistics sfStatistics = session.getSessionFactory().getStatistics(); assertSame( sfStatistics.getCollectionFetchCount(), 1L ); assertSame( sfStatistics.getQueries().length, 1 ); } ); }
@Test public void testEntitySQLOverriding() { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); Chaos chaos = new Chaos(); chaos.setSize( 123l ); chaos.setId( 1l ); String lowerName = "hello"; String upperName = lowerName.toUpperCase(Locale.ROOT); assertFalse( lowerName.equals( upperName ) ); chaos.setName( "hello" ); chaos.setNickname( "NickName" ); s.persist( chaos ); s.flush(); s.clear(); s.getSessionFactory().getCache().evictEntityRegion( Chaos.class ); Chaos resultChaos = s.load( Chaos.class, chaos.getId() ); assertEquals( upperName, resultChaos.getName() ); assertEquals( "nickname", resultChaos.getNickname() ); tx.rollback(); s.close(); }