public static SessionFactory getSessionFactory() { if (null != sessionFactory) return sessionFactory; Configuration configuration = new Configuration(); String jdbcUrl = "jdbc:mysql://" + System.getenv("RDS_HOSTNAME") + "/" + System.getenv("RDS_DB_NAME"); configuration.setProperty("hibernate.connection.url", jdbcUrl); configuration.setProperty("hibernate.connection.username", System.getenv("RDS_USERNAME")); configuration.setProperty("hibernate.connection.password", System.getenv("RDS_PASSWORD")); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); try { sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (HibernateException e) { System.err.println("Initial SessionFactory creation failed." + e); throw new ExceptionInInitializerError(e); } return sessionFactory; }
@Test public void withActiveSpanOnlyNoParent() throws InterruptedException { SessionFactory sessionFactory = createSessionFactory(";traceWithActiveSpanOnly=true"); Session session = sessionFactory.openSession(); Employee employee = new Employee(); session.beginTransaction(); session.save(employee); session.getTransaction().commit(); session.close(); sessionFactory.close(); List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertEquals(0, finishedSpans.size()); assertNull(mockTracer.scopeManager().active()); }
public SpringSessionSynchronization( SessionHolder sessionHolder, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator, boolean newSession) { this.sessionHolder = sessionHolder; this.sessionFactory = sessionFactory; this.jdbcExceptionTranslator = jdbcExceptionTranslator; this.newSession = newSession; // Check whether the SessionFactory has a JTA TransactionManager. TransactionManager jtaTm = SessionFactoryUtils.getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession()); if (jtaTm != null) { this.hibernateTransactionCompletion = true; // Fetch current JTA Transaction object // (just necessary for JTA transaction suspension, with an individual // Hibernate Session per currently active/suspended transaction). try { this.jtaTransaction = jtaTm.getTransaction(); } catch (SystemException ex) { throw new DataAccessResourceFailureException("Could not access JTA transaction", ex); } } }
@Override public long getNumberOfEntities(SessionFactory sessionFactory) { RedisClusterCommands<String, String> connection = getConnection( sessionFactory ); List<String> keys = connection.keys( "*" ); long result = 0; for ( String key : keys ) { if ( key.startsWith( AbstractRedisDialect.ASSOCIATIONS ) || key.startsWith( AbstractRedisDialect.IDENTIFIERS ) ) { continue; } String type = connection.type( key ); if ( type.equals( "hash" ) || type.equals( "string" ) ) { result++; } } return result; }
@Override public long getNumberOfAssociations(SessionFactory sessionFactory) { int associationCount = 0; IgniteDatastoreProvider datastoreProvider = getProvider( sessionFactory ); for ( CollectionPersister collectionPersister : ( (SessionFactoryImplementor) sessionFactory ).getCollectionPersisters().values() ) { AssociationKeyMetadata associationKeyMetadata = ( (OgmCollectionPersister) collectionPersister ).getAssociationKeyMetadata(); if ( associationKeyMetadata.getAssociationKind() == AssociationKind.ASSOCIATION ) { IgniteCache<Object, BinaryObject> associationCache = getAssociationCache( sessionFactory, associationKeyMetadata ); StringBuilder query = new StringBuilder( "SELECT " ) .append( StringHelper.realColumnName( associationKeyMetadata.getColumnNames()[0] ) ) .append( " FROM " ).append( associationKeyMetadata.getTable() ); SqlFieldsQuery sqlQuery = datastoreProvider.createSqlFieldsQueryWithLog( query.toString(), null ); Iterable<List<?>> queryResult = associationCache.query( sqlQuery ); Set<Object> uniqs = new HashSet<>(); for ( List<?> row : queryResult ) { Object value = row.get( 0 ); if ( value != null ) { uniqs.add( value ); } } associationCount += uniqs.size(); } } return associationCount; }
private int queryForInt(String hql,Object[] parameters,Map<String,Object> parameterMap,String dataSourceName){ SessionFactory factory=this.getSessionFactory(dataSourceName); Session session=factory.openSession(); int count=0; try{ Query countQuery=session.createQuery(hql); if(parameters!=null){ setQueryParameters(countQuery,parameters); }else if(parameterMap!=null){ setQueryParameters(countQuery,parameterMap); } Object countObj=countQuery.uniqueResult(); if(countObj instanceof Long){ count=((Long)countObj).intValue(); }else if(countObj instanceof Integer){ count=((Integer)countObj).intValue(); } }finally{ session.close(); } return count; }
/** * Process all Hibernate Sessions that have been registered for deferred close * for the given SessionFactory. * @param sessionFactory the Hibernate SessionFactory to process deferred close for * @see #initDeferredClose * @see #releaseSession */ public static void processDeferredClose(SessionFactory sessionFactory) { Assert.notNull(sessionFactory, "No SessionFactory specified"); Map<SessionFactory, Set<Session>> holderMap = deferredCloseHolder.get(); if (holderMap == null || !holderMap.containsKey(sessionFactory)) { throw new IllegalStateException("Deferred close not active for SessionFactory [" + sessionFactory + "]"); } logger.debug("Processing deferred close of Hibernate Sessions"); Set<Session> sessions = holderMap.remove(sessionFactory); for (Session session : sessions) { closeSession(session); } if (holderMap.isEmpty()) { deferredCloseHolder.remove(); } }
@Test public void testGetAdmin(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); Admin admin = (Admin) session.get(Admin.class, 1); System.out.println(admin); System.out.println(admin.getAuthorization().getSuperSet()); session.close(); }
synchronized SessionFactory getSessionFactory() { if( sessionFactory == null ) { sessionFactory = getHibernateFactory().getSessionFactory(); } return sessionFactory; }
/** * 获得记录总数 */ @Override public Integer getCountOfAllNewsInfo() { Session session = SessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(NewsInfo.class); return criteria.list().size(); }
private static SessionFactory getSessionFactory() { if (HibernateSessionManager.sessionFactory == null) { WebApplicationContext wac = WebApplicationContextUtils .getRequiredWebApplicationContext(SessionManager.getServletContext()); HibernateSessionManager.sessionFactory = (SessionFactory) wac.getBean("coreSessionFactory"); } return HibernateSessionManager.sessionFactory; }
@Override public void dropSchemaAndDatabase(SessionFactory sessionFactory) { if ( Ignition.allGrids().size() > 1 ) { // some tests doesn't stop DatastareProvider String currentGridName = getProvider( sessionFactory ).getGridName(); for ( Ignite grid : Ignition.allGrids() ) { if ( !Objects.equals( currentGridName, grid.name() ) ) { grid.close(); } } } }
@Test public void testSaveAdmin(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Admin admin = new Admin(); admin.setName("cairou"); admin.setUsername("admin"); admin.setPwd(Md5Utils.md5("admin")); session.save(admin); transaction.commit(); session.close(); }
@Bean(name = "transactionManager") public HibernateTransactionManager getTransactionManager( SessionFactory sessionFactory) { HibernateTransactionManager transactionManager = new HibernateTransactionManager( sessionFactory); return transactionManager; }
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { sessionFactoryBeanList = applicationContext.getBeansOfType(HibernateSessionFactory.class) .values(); for (HibernateSessionFactory bean : sessionFactoryBeanList) { SessionFactory sessionFactory = bean.getObject(); sessionFactoryMap.put(bean.getDataSourceName(), sessionFactory); if (bean.isAsDefault()) { defaultSessionFactory = sessionFactory; defaultSessionFactoryName = bean.getDataSourceName(); } } }
@Inject public StatisticConfigurationServiceImpl(final CacheFactory cacheFactory, final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO, final StatisticConfigurationCacheByUuidLoaderWriter byUuidLoaderWriter, final SessionFactory sessionFactory) { this.stroomStatsStoreEntityDAO = stroomStatsStoreEntityDAO; this.sessionFactory = sessionFactory; this.keyByUuidCache = cacheFactory.getOrCreateCache( KEY_BY_UUID_CACHE_NAME, String.class, StatisticConfiguration.class, Optional.of(byUuidLoaderWriter)); }
@Test public void testSaveBorrow(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); BorrowInfo borrowInfo = new BorrowInfo(); Admin admin = new Admin(); admin.setAid(2); borrowInfo.setAdmin(admin); session.save(borrowInfo); transaction.commit(); session.close(); }
@Test public void testGetAdmin3(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); Authorization authorization = (Authorization) session.get(Authorization.class, 1); System.out.println(authorization.getAdmin().getName()); session.close(); }
protected Session _open_session( String _db ) { if ( sessionFactoryMap.containsKey( _db ) ) { SessionFactory sessFactory = sessionFactoryMap.get( _db ); return sessFactory.openSession(); } throw new NullPointerException( "没有找到数据库[" + _db + "]的对应Session容器,请检查配置文件中的[ " + DEFAULT_SFMAP + " ]是否正确。" ); }
@Override public void sessionFactoryClosed(SessionFactory factory) { if ( observers == null ) { return; } //notify in reverse order of create notification int size = observers.size(); for (int index = size - 1 ; index >= 0 ; index--) { observers.get( index ).sessionFactoryClosed( factory ); } }
private SessionFactory createSessionFactory() { SessionFactory sessionFactory = null; try { String resource; Configuration configuration = new Configuration(); resource = "oswf-store.cfg.xml"; logger.info("Configuring Hibernate Mapping: " + resource); configuration.configure(resource); // Database configuration; H2 or MySQL resource = "hibernate.xml"; logger.info("Configuring Hibernate Mapping: " + resource); configuration.configure(resource); // Attempt to create the SessionFactory; exceptions may be thrown sessionFactory = configuration.buildSessionFactory(); } catch (Throwable e) { logger.error(fatal, "Failed to create Hibernate SessionFactory: " + e.toString()); sessionFactory = null; } return sessionFactory; }
/** * Close the given Session, created via the given factory, * if it is not managed externally (i.e. not bound to the thread). * @param session the Hibernate Session to close (may be {@code null}) * @param sessionFactory Hibernate SessionFactory that the Session was created with * (may be {@code null}) */ public static void releaseSession(Session session, SessionFactory sessionFactory) { if (session == null) { return; } // Only close non-transactional Sessions. if (!isSessionTransactional(session, sessionFactory)) { closeSessionOrRegisterDeferredClose(session, sessionFactory); } }
/** * Look up the SessionFactory that this filter should use. * <p>The default implementation looks for a bean with the specified name * in Spring's root application context. * @return the SessionFactory to use * @see #getSessionFactoryBeanName */ protected SessionFactory lookupSessionFactory() { if (logger.isDebugEnabled()) { logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter"); } WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class); }
public HibernateStore(Map<String,String> config, Map<String,Object> parameters) throws WorkflowStoreException { super(config, parameters); sessionFactory = (SessionFactory)parameters.get("sessionFactory"); if(sessionFactory == null) throw new WorkflowStoreException("Hibernate SessionFactory not configured in persistence store"); }
/** * Get a new Hibernate Session from the given SessionFactory. * Will return a new Session even if there already is a pre-bound * Session for the given SessionFactory. * <p>Within a transaction, this method will create a new Session * that shares the transaction's JDBC Connection. More specifically, * it will use the same JDBC Connection as the pre-bound Hibernate Session. * @param sessionFactory Hibernate SessionFactory to create the session with * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none * @return the new Session */ @SuppressWarnings("deprecation") public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) { Assert.notNull(sessionFactory, "No SessionFactory specified"); try { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && !sessionHolder.isEmpty()) { if (entityInterceptor != null) { return sessionFactory.openSession(sessionHolder.getAnySession().connection(), entityInterceptor); } else { return sessionFactory.openSession(sessionHolder.getAnySession().connection()); } } else { if (entityInterceptor != null) { return sessionFactory.openSession(entityInterceptor); } else { return sessionFactory.openSession(); } } } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
@Test public void testFindBook(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); String hql= "from Book"; List createQuery = session.createQuery(hql).list(); Book book = (Book) createQuery.get(0); System.out.println(book); System.out.println(book.getBookType()); }
@DataResolver public void saveCalendars(Collection<JobCalendar> calendars){ SessionFactory sessionFactory=this.getSessionFactory(); Session session=sessionFactory.openSession(); try{ for(JobCalendar c:calendars){ EntityState state=EntityUtils.getState(c); if(state.equals(EntityState.NEW)){ c.setId(UUID.randomUUID().toString()); c.setCompanyId(dataService.getCompanyId()); session.save(c); } if(state.equals(EntityState.MODIFIED)){ session.update(c); } if(state.equals(EntityState.DELETED)){ String hql="select count(*) from "+JobCalendarRelation.class.getName()+" where calendarId=:calendarId"; Map<String,Object> map=new HashMap<String,Object>(); map.put("calendarId", c.getId()); int count=this.queryForInt(hql, map); if(count>0){ throw new RuntimeException("当前日期有Job正在使用,不能被删除"); } hql="delete "+JobCalendarDate.class.getName()+" where calendarId=:calendarId"; session.createQuery(hql).setString("calendarId", c.getId()).executeUpdate(); session.delete(c); } if(c.getCalendarDates()!=null){ this.saveCalendarDates(c.getCalendarDates(), session); } } }finally{ session.flush(); session.close(); } }
@Test public void testSaveAdmin3(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Authorization authorization = new Authorization(); authorization.setAid(2); session.save(authorization); transaction.commit(); session.close(); }
public SessionFactory getSessionFactory() { return getTxManager().getSessionFactory(); }
public SessionFactory getSessionFactory() { return sessionFactory; }
@Autowired public playerDaoImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; }
public void setSessions(SessionFactory sessions) { this.sessions = sessions; }
@Autowired public votesDaoImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; }
@Autowired public KnockoutScoreDaoImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; }
public SessionFactory getDefaultSessionFactory() { return defaultSessionFactory; }
public AbstractHibernateDao(Class<T> entityClass, SessionFactory sessionFactory) { this.entityClass = entityClass; this.sessionFactory = sessionFactory; }
public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; }
public PlayerService(SessionFactory sessionFactory) { super(sessionFactory); }
public DaoMethodPreHandler(SessionFactory sessionFactory) { this.dao = new HibernatePartitionDaoImpl(sessionFactory); }