Java Code Examples for org.hibernate.SessionFactory

The following examples show how to use org.hibernate.SessionFactory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: tutorials   Source File: HibernateLifecycleUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenTransientEntity_whenSave_thenManaged() throws Exception {
    SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = startTransaction(session);

        FootballPlayer neymar = new FootballPlayer();
        neymar.setName("Neymar");

        session.save(neymar);
        assertThat(getManagedEntities(session)).size().isEqualTo(1);
        assertThat(neymar.getId()).isNotNull();

        int count = queryCount("select count(*) from Football_Player where name='Neymar'");
        assertThat(count).isEqualTo(0);

        transaction.commit();

        count = queryCount("select count(*) from Football_Player where name='Neymar'");
        assertThat(count).isEqualTo(1);

        transaction = startTransaction(session);
        session.delete(neymar);
        transaction.commit();
    }
}
 
Example 2
Source Project: ignite   Source File: HibernateL2CacheSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param sesFactory Session factory.
 * @param idToChildCnt Number of children per entity.
 * @param expHit Expected cache hits.
 * @param expMiss Expected cache misses.
 */
@SuppressWarnings("unchecked")
private void assertCollectionCache(SessionFactory sesFactory, Map<Integer, Integer> idToChildCnt, int expHit,
    int expMiss) {
    sesFactory.getStatistics().clear();

    Session ses = sesFactory.openSession();

    try {
        for (Map.Entry<Integer, Integer> e : idToChildCnt.entrySet()) {
            Entity entity = (Entity)ses.load(Entity.class, e.getKey());

            assertEquals((int)e.getValue(), entity.getChildren().size());
        }
    }
    finally {
        ses.close();
    }

    SecondLevelCacheStatistics stats =
        sesFactory.getStatistics().getSecondLevelCacheStatistics(CHILD_COLLECTION_REGION);

    assertEquals(expHit, stats.getHitCount());

    assertEquals(expMiss, stats.getMissCount());
}
 
Example 3
Source Project: Transwarp-Sample-Code   Source File: InHibernate.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
    String path = "hibernate.cfg.xml";
    Configuration cfg = new Configuration().configure(path);

    SessionFactory sessionFactory = cfg.buildSessionFactory();

    Session session = sessionFactory.openSession();
    session.beginTransaction();
    User user = new User();
    user.setId("443");
    user.setName("baa");
    session.save(user);
    // session.close();
    session.getTransaction().commit();
    sessionFactory.close();
}
 
Example 4
Source Project: lams   Source File: SessionFactoryImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static SessionFactory locateSessionFactoryOnDeserialization(String uuid, String name) throws InvalidObjectException{
	final SessionFactory uuidResult = SessionFactoryRegistry.INSTANCE.getSessionFactory( uuid );
	if ( uuidResult != null ) {
		LOG.debugf( "Resolved SessionFactory by UUID [%s]", uuid );
		return uuidResult;
	}

	// in case we were deserialized in a different JVM, look for an instance with the same name
	// (provided we were given a name)
	if ( name != null ) {
		final SessionFactory namedResult = SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( name );
		if ( namedResult != null ) {
			LOG.debugf( "Resolved SessionFactory by name [%s]", name );
			return namedResult;
		}
	}

	throw new InvalidObjectException( "Could not find a SessionFactory [uuid=" + uuid + ",name=" + name + "]" );
}
 
Example 5
Source Project: megatron-java   Source File: DbManager.java    License: Apache License 2.0 6 votes vote down vote up
protected DbManager()

            throws DbException { 

        this.log = Logger.getLogger(this.getClass());

        try {
            // This step will read hibernate.cfg.xml             
            //    and prepare hibernate for use
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();            
            session = sessionFactory.openSession();
        }
        catch (HibernateException he) {                    
            he.printStackTrace();
            throw new DbException("Failed to initialize DbManager", he);
        }              
    }
 
Example 6
Source Project: java-technology-stack   Source File: OpenSessionInterceptor.java    License: MIT License 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	Assert.state(sf != null, "No SessionFactory set");

	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession(sf);
		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();
	}
}
 
Example 7
Source Project: Project   Source File: CRUDTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void selectTest(){
    Configuration configuration = new Configuration();
    configuration.configure();

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    User user = session.get(User.class, 1);
    System.out.println(user);

    transaction.commit();

    session.close();
    sessionFactory.close();
}
 
Example 8
public void init() {
    if (incNestingCount() > 1) {
        return;
    }
    SessionFactory sf = getSessionFactory();
    if (sf == null) {
        return;
    }
    if (TransactionSynchronizationManager.hasResource(sf)) {
        // Do not modify the Session: just set the participate flag.
        setParticipate(true);
    }
    else {
        setParticipate(false);
        LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor");
        Session session = getSession();
        HibernateRuntimeUtils.enableDynamicFilterEnablerIfPresent(sf, session);
        TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    }
}
 
Example 9
Source Project: journaldev   Source File: HibernateMergeExample.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {

		// Prep Work
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		Employee emp = (Employee) session.load(Employee.class, new Long(101));
		System.out.println("Employee object loaded. " + emp);
		tx.commit();

		 //merge example - data already present in tables
		 emp.setSalary(25000);
		 Transaction tx8 = session.beginTransaction();
		 Employee emp4 = (Employee) session.merge(emp);
		 System.out.println(emp4 == emp); // returns false
		 emp.setName("Test");
		 emp4.setName("Kumar");
		 System.out.println("15. Before committing merge transaction");
		 tx8.commit();
		 System.out.println("16. After committing merge transaction");

		// Close resources
		sessionFactory.close();

	}
 
Example 10
@Override
@Nullable
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);
	}
}
 
Example 11
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheRegionFactory() throws Exception {
	final RegionFactory regionFactory = new NoCachingRegionFactory(null);
	final List invocations = new ArrayList();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected Configuration newConfiguration() {
			return new Configuration() {
				@Override
				public Configuration addInputStream(InputStream is) {
					try {
						is.close();
					}
					catch (IOException ex) {
					}
					invocations.add("addResource");
					return this;
				}
			};
		}
		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(LocalRegionFactoryProxy.class.getName(),
					config.getProperty(Environment.CACHE_REGION_FACTORY));
			assertSame(regionFactory, LocalSessionFactoryBean.getConfigTimeRegionFactory());
			invocations.add("newSessionFactory");
			return null;
		}
	};
	sfb.setCacheRegionFactory(regionFactory);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertEquals("newSessionFactory", invocations.get(0));
}
 
Example 12
@Override
public void sessionFactoryClosed(SessionFactory sessionFactory) {
	SessionFactoryImplementor sfi = ( (SessionFactoryImplementor) sessionFactory );
	sfi.getServiceRegistry().destroy();
	ServiceRegistry basicRegistry = sfi.getServiceRegistry().getParentServiceRegistry();
	( (ServiceRegistryImplementor) basicRegistry ).destroy();
}
 
Example 13
private static void deleteGeometry(SessionFactory sessionFactory) {
    Session session = sessionFactory.openSession();

    session.beginTransaction();

    Query query = session.createQuery("delete from TheData where id=:id");
    query.setParameter("id",1L);
    query.executeUpdate();

    session.getTransaction().commit();
    session.close();
}
 
Example 14
public void stop() {
	log.info("stopping service");
	try {
		InitialContext context = NamingHelper.getInitialContext( buildProperties() );
		( (SessionFactory) context.lookup(boundName) ).close();
		//context.unbind(boundName);
	}
	catch (Exception e) {
		log.warn("exception while stopping service", e);
	}
}
 
Example 15
Source Project: spring-analysis-note   Source File: OpenSessionInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * Open a Session for the given SessionFactory.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory to use
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @since 5.0
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = openSession();
	if (session == null) {
		try {
			session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.MANUAL);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
		}
	}
	return session;
}
 
Example 16
@Test
void set_metadata_from_dump(SessionFactory sessionFactory) {
    ExampleHibernateDao dao = new ExampleHibernateDao(sessionFactory, new TestClock(), new TestActorProvider());

    TestDump testRestoreDump = new TestDump.Builder()
            .mode(DumpImportMode.RESTORE)
            .createdBy("createdBy1")
            .createdIp("createdIp1")
            .createdAt(Instant.ofEpochSecond(23))
            .updatedBy("updatedBy1")
            .updatedIp("updatedIp1")
            .updatedAt(Instant.ofEpochSecond(77))
            .build();

    ExampleModel model = new ExampleModel();
    dao.setModelMetadataFromDump(model, testRestoreDump);

    assertThat(model.createdBy).isEqualTo("createdBy1");
    assertThat(model.createdIp).isEqualTo("createdIp1");
    assertThat(model.createdAt).isEqualTo(Instant.ofEpochSecond(23));
    assertThat(model.updatedBy).isEqualTo("updatedBy1");
    assertThat(model.updatedIp).isEqualTo("updatedIp1");
    assertThat(model.updatedAt).isEqualTo(Instant.ofEpochSecond(77));

    dao.setModelMetadataFromDump(model, new TestDump.Builder()
            .from(testRestoreDump)
            .mode(DumpImportMode.CREATE)
            .build());

    assertThat(model.createdBy).isEqualTo("actorJid");
    assertThat(model.createdIp).isEqualTo("actorIp");
    assertThat(model.createdAt).isEqualTo(TestClock.NOW);
    assertThat(model.updatedBy).isEqualTo("actorJid");
    assertThat(model.updatedIp).isEqualTo("actorIp");
    assertThat(model.updatedAt).isEqualTo(TestClock.NOW);
}
 
Example 17
Source Project: tutorials   Source File: QueryPlanCacheBenchmark.java    License: MIT License 5 votes vote down vote up
@TearDown
public void tearDownState() {
    LOGGER.info("State - Teardown");
    SessionFactory sessionFactory = session.getSessionFactory();
    session.close();
    sessionFactory.close();
    LOGGER.info("State - Teardown complete");
}
 
Example 18
Source Project: maven-framework-project   Source File: HibernateUtil.java    License: MIT License 5 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
        return new AnnotationConfiguration()
        		.configure()
                .buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 19
Source Project: dropwizard-jaxws   Source File: JAXWSEnvironmentTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {

    ((ch.qos.logback.classic.Logger)LoggerFactory.getLogger("org.apache.cxf")).setLevel(Level.INFO);

    jaxwsEnvironment = new JAXWSEnvironment("soap") {
        /*
        We create BasicAuthenticationInterceptor mock manually, because Mockito provided mock
        does not get invoked by CXF
        */
        @Override
        protected BasicAuthenticationInterceptor createBasicAuthenticationInterceptor() {
            return new BasicAuthenticationInterceptor() {
                @Override
                public void handleMessage(Message message) throws Fault {
                    mockBasicAuthInterceptorInvoked++;
                }
            };
        }
    };

    when(mockInvokerBuilder.create(any(), any(Invoker.class))).thenReturn(mockInvoker);
    jaxwsEnvironment.setInstrumentedInvokerBuilder(mockInvokerBuilder);

    when(mockUnitOfWorkInvokerBuilder
            .create(any(), any(Invoker.class), any(SessionFactory.class)))
            .thenReturn(mockInvoker);
    jaxwsEnvironment.setUnitOfWorkInvokerBuilder(mockUnitOfWorkInvokerBuilder);

    mockBasicAuthInterceptorInvoked = 0;

    testutils.setBus(jaxwsEnvironment.bus);
    testutils.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
    testutils.addNamespace("a", "http://jaxws.dropwizard.roskart.com/");
}
 
Example 20
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
        SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(
            sessionFactory);
    return transactionManager;
}
 
Example 21
Source Project: blog   Source File: GreetingServiceConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public HibernateTransactionManager transactionManager(
		SessionFactory sessionFactory) {
	HibernateTransactionManager htm = new HibernateTransactionManager();
	htm.setSessionFactory(sessionFactory);
	return htm;
}
 
Example 22
Source Project: sailfish-core   Source File: SFLocalContext.java    License: Apache License 2.0 5 votes vote down vote up
private IServiceStorage createServiceStorage(EnvironmentSettings envSettings, SessionFactory sessionFactory, IWorkspaceDispatcher workspaceDispatcher, IStaticServiceManager staticServiceManager, IDictionaryManager dictionaryManager,
           IMessageStorage messageStorage) {
       switch(envSettings.getStorageType()) {
       case DB:
           return new DatabaseServiceStorage(sessionFactory, staticServiceManager, dictionaryManager, messageStorage);
	case FILE:
           return new FileServiceStorage(envSettings.getFileStoragePath(), workspaceDispatcher, staticServiceManager, messageStorage);
       case MEMORY:
           return new MemoryServiceStorage();
	default:
           throw new EPSCommonException("Unsupported service storage type. Check your descriptor.xml file.");
	}
}
 
Example 23
Source Project: ignite   Source File: HibernateL2CacheSelfTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts Hibernate.
 *
 * @param accessType Cache access type.
 * @param igniteInstanceName Ignite instance name.
 * @return Session factory.
 */
private SessionFactory startHibernate(org.hibernate.cache.spi.access.AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = registryBuilder();

    for (Map.Entry<String, String> e : hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    // Use the same cache for Entity and Entity2.
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, ENTITY_NAME);

    StandardServiceRegistry srvcRegistry = builder.build();

    MetadataSources metadataSources = new MetadataSources(srvcRegistry);

    for (Class entityClass : getAnnotatedClasses())
        metadataSources.addAnnotatedClass(entityClass);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass) entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    for (org.hibernate.mapping.Collection collectionBinding : metadata.getCollectionBindings())
        collectionBinding.setCacheConcurrencyStrategy(accessType.getExternalName());

    return metadata.buildSessionFactory();
}
 
Example 24
@Override
protected SessionFactory newSessionFactory() {
    Properties properties = getProperties();

    return new Configuration()
            .addProperties(properties)
            .addAnnotatedClass(SecurityId.class)
            .buildSessionFactory(
                    new StandardServiceRegistryBuilder()
                            .applySettings(properties)
                            .build()
            );
}
 
Example 25
Source Project: aw-reporting   Source File: SqlReportEntitiesPersister.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param sessionFactory the session factory to communicate with the DB.
 */
@Autowired
public SqlReportEntitiesPersister(SessionFactory sessionFactory, Config config) {
  this.sessionFactory =
      Preconditions.checkNotNull(sessionFactory, "SessionFactory can not be null");
  this.config = Preconditions.checkNotNull(config, "Config can not be null");
}
 
Example 26
Source Project: lams   Source File: SessionFactoryRegistry.java    License: GNU General Public License v2.0 5 votes vote down vote up
public SessionFactory findSessionFactory(String uuid, String name) {
	SessionFactory sessionFactory = getSessionFactory( uuid );
	if ( sessionFactory == null && StringHelper.isNotEmpty( name ) ) {
		sessionFactory = getNamedSessionFactory( name );
	}
	return sessionFactory;
}
 
Example 27
Source Project: gocd   Source File: PipelineStateDao.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public PipelineStateDao(GoCache goCache,
                        TransactionTemplate transactionTemplate,
                        SqlSessionFactory sqlSessionFactory,
                        TransactionSynchronizationManager transactionSynchronizationManager,
                        SystemEnvironment systemEnvironment,
                        Database database,
                        SessionFactory sessionFactory) {
    super(goCache, sqlSessionFactory, systemEnvironment, database);
    this.transactionTemplate = transactionTemplate;
    this.transactionSynchronizationManager = transactionSynchronizationManager;
    this.sessionFactory = sessionFactory;
    this.cacheKeyGenerator = new CacheKeyGenerator(getClass());
}
 
Example 28
Source Project: lams   Source File: ManagedSessionContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unbinds the session (if one) current associated with the context for the
 * given session.
 *
 * @param factory The factory for which to unbind the current session.
 * @return The bound session if one, else null.
 */
public static Session unbind(SessionFactory factory) {
	final Map<SessionFactory,Session> sessionMap = sessionMap();
	Session existing = null;
	if ( sessionMap != null ) {
		existing = sessionMap.remove( factory );
		doCleanup();
	}
	return existing;
}
 
Example 29
Source Project: spring4-understanding   Source File: SessionFactoryUtils.java    License: Apache License 2.0 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 30
public void testSessionStats() throws Exception {
	
	SessionFactory sf = getSessions();
	Statistics stats = sf.getStatistics();
	boolean isStats = stats.isStatisticsEnabled();
	stats.clear();
	stats.setStatisticsEnabled(true);
	Session s = sf.openSession();
	assertEquals( 1, stats.getSessionOpenCount() );
	s.close();
	assertEquals( 1, stats.getSessionCloseCount() );
	s = sf.openSession();
	Transaction tx = s.beginTransaction();
	A a = new A();
	a.setName("mya");
	s.save(a);
	a.setName("b");
	tx.commit();
	s.close();
	assertEquals( 1, stats.getFlushCount() );
	s = sf.openSession();
	tx = s.beginTransaction();
	String hql = "from " + A.class.getName();
	Query q = s.createQuery(hql);
	q.list();
	tx.commit();
	s.close();
	assertEquals(1, stats.getQueryExecutionCount() );
	assertEquals(1, stats.getQueryStatistics(hql).getExecutionCount() );
	
	stats.setStatisticsEnabled(isStats);
}