Java Code Examples for org.hibernate.SessionFactory

The following are top voted examples for showing how to use org.hibernate.SessionFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lambda-rds-mysql   File: HibernateUtil.java   View source code 8 votes vote down vote up
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;
}
 
Example 2
Project: lams   File: SpringSessionSynchronization.java   View source code 7 votes vote down vote up
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);
		}
	}
}
 
Example 3
Project: java-p6spy   File: HibernateTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 4
Project: hibernate-ogm-redis   File: RedisTestHelper.java   View source code 6 votes vote down vote up
@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;
}
 
Example 5
Project: hibernate-ogm-ignite   File: IgniteTestHelper.java   View source code 6 votes vote down vote up
@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;
}
 
Example 6
Project: bdf2   File: HibernateDao.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: lams   File: SessionFactoryUtils.java   View source code 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 8
Project: LibrarySystem   File: TestAdmin.java   View source code 5 votes vote down vote up
@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();
	
}
 
Example 9
Project: Equella   File: HibernateMigrationService.java   View source code 5 votes vote down vote up
synchronized SessionFactory getSessionFactory()
{
	if( sessionFactory == null )
	{
		sessionFactory = getHibernateFactory().getSessionFactory();
	}
	return sessionFactory;
}
 
Example 10
Project: NewsSystem   File: NewsInfoDAOImpl.java   View source code 5 votes vote down vote up
/**
 * 获得记录总数
 */
@Override
public Integer getCountOfAllNewsInfo() {
	Session session = SessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(NewsInfo.class);
	return criteria.list().size();
}
 
Example 11
Project: lams   File: HibernateSessionManager.java   View source code 5 votes vote down vote up
private static SessionFactory getSessionFactory() {
if (HibernateSessionManager.sessionFactory == null) {
    WebApplicationContext wac = WebApplicationContextUtils
	    .getRequiredWebApplicationContext(SessionManager.getServletContext());
    HibernateSessionManager.sessionFactory = (SessionFactory) wac.getBean("coreSessionFactory");
}
return HibernateSessionManager.sessionFactory;
   }
 
Example 12
Project: hibernate-ogm-ignite   File: IgniteTestHelper.java   View source code 5 votes vote down vote up
@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();
			}
		}
	}
}
 
Example 13
Project: LibrarySystem   File: TestAdmin.java   View source code 5 votes vote down vote up
@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();
}
 
Example 14
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: AppConfig.java   View source code 5 votes vote down vote up
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
        SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(
            sessionFactory);
    return transactionManager;
}
 
Example 15
Project: bdf2   File: HibernateSessionFactoryRepository.java   View source code 5 votes vote down vote up
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();
		}
	}
}
 
Example 16
Project: stroom-stats   File: StatisticConfigurationServiceImpl.java   View source code 5 votes vote down vote up
@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));
}
 
Example 17
Project: LibrarySystem   File: TestBorrow.java   View source code 5 votes vote down vote up
@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();
}
 
Example 18
Project: LibrarySystem   File: TestAdmin.java   View source code 5 votes vote down vote up
@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();
}
 
Example 19
Project: jeesupport   File: AbsSupportDao.java   View source code 5 votes vote down vote up
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 + " ]是否正确。" );
}
 
Example 20
Project: lams   File: SessionFactoryObserverChain.java   View source code 5 votes vote down vote up
@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 );
	}
}
 
Example 21
Project: OSWf-OSWorkflow-fork   File: StartupContextListener.java   View source code 5 votes vote down vote up
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;
}
 
Example 22
Project: lams   File: SessionFactoryUtils.java   View source code 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 23
Project: lams   File: OpenSessionInViewFilter.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 24
Project: OSWf-OSWorkflow-fork   File: HibernateStore.java   View source code 5 votes vote down vote up
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");
}
 
Example 25
Project: lams   File: SessionFactoryUtils.java   View source code 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 26
Project: LibrarySystem   File: TestBook.java   View source code 5 votes vote down vote up
@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());
}
 
Example 27
Project: bdf2   File: CalendarMaintain.java   View source code 5 votes vote down vote up
@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();
	}
}
 
Example 28
Project: LibrarySystem   File: TestAdmin.java   View source code 5 votes vote down vote up
@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();
}
 
Example 29
Project: sbc-qsystem   File: Spring.java   View source code 4 votes vote down vote up
public SessionFactory getSessionFactory() {
    return getTxManager().getSessionFactory();
}
 
Example 30
Project: uflo   File: HeartJobDetail.java   View source code 4 votes vote down vote up
public SessionFactory getSessionFactory() {
	return sessionFactory;
}
 
Example 31
Project: theLXGweb   File: playerDaoImpl.java   View source code 4 votes vote down vote up
@Autowired
public playerDaoImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
 
Example 32
Project: sjk   File: AbstractBaseDao.java   View source code 4 votes vote down vote up
public void setSessions(SessionFactory sessions) {
    this.sessions = sessions;
}
 
Example 33
Project: theLXGweb   File: votesDaoImpl.java   View source code 4 votes vote down vote up
@Autowired
public votesDaoImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
 
Example 34
Project: theLXGweb   File: KnockoutScoreDaoImpl.java   View source code 4 votes vote down vote up
@Autowired
public KnockoutScoreDaoImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
 
Example 35
Project: bdf2   File: HibernateSessionFactoryRepository.java   View source code 4 votes vote down vote up
public SessionFactory getDefaultSessionFactory() {
	return defaultSessionFactory;
}
 
Example 36
Project: rjb-blog-multitenancy   File: AbstractHibernateDao.java   View source code 4 votes vote down vote up
public AbstractHibernateDao(Class<T> entityClass, SessionFactory sessionFactory) {
	this.entityClass = entityClass;
	this.sessionFactory = sessionFactory;
}
 
Example 37
Project: baseframe-partition   File: BasePartitionService.java   View source code 4 votes vote down vote up
public void setSessionFactory(SessionFactory sessionFactory) {
	this.sessionFactory = sessionFactory;
}
 
Example 38
Project: cr-private-server   File: PlayerService.java   View source code 4 votes vote down vote up
public PlayerService(SessionFactory sessionFactory) {
	super(sessionFactory);
}
 
Example 39
Project: Restaurant   File: ProductDaoImpl.java   View source code 4 votes vote down vote up
public void setSessionFactory(SessionFactory sessionFactory) {
	this.sessionFactory = sessionFactory;
}
 
Example 40
Project: baseframe-partition   File: DaoMethodPreHandler.java   View source code 4 votes vote down vote up
public DaoMethodPreHandler(SessionFactory sessionFactory) {
    this.dao = new HibernatePartitionDaoImpl(sessionFactory);
}