org.hibernate.SessionFactory Java Examples
The following examples show how to use
org.hibernate.SessionFactory.
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 check out the related API usage on the sidebar.
Example #1
Source File: InHibernate.java From Transwarp-Sample-Code with MIT License | 8 votes |
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 #2
Source File: HibernateL2CacheSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @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 File: CRUDTest.java From Project with Apache License 2.0 | 6 votes |
@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 #4
Source File: SessionFactoryImpl.java From lams with GNU General Public License v2.0 | 6 votes |
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 File: HibernatePersistenceContextInterceptor.java From gorm-hibernate5 with Apache License 2.0 | 6 votes |
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 #6
Source File: DbManager.java From megatron-java with Apache License 2.0 | 6 votes |
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 #7
Source File: OpenSessionInterceptor.java From java-technology-stack with MIT License | 6 votes |
@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 #8
Source File: HibernateLifecycleUnitTest.java From tutorials with MIT License | 6 votes |
@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 #9
Source File: HibernateMergeExample.java From journaldev with MIT License | 6 votes |
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
Source File: GreetingServiceConfig.java From blog with Apache License 2.0 | 5 votes |
@Bean public HibernateTransactionManager transactionManager( SessionFactory sessionFactory) { HibernateTransactionManager htm = new HibernateTransactionManager(); htm.setSessionFactory(sessionFactory); return htm; }
Example #11
Source File: PipelineStateDao.java From gocd with Apache License 2.0 | 5 votes |
@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 #12
Source File: AppConfig.java From Building-Web-Apps-with-Spring-5-and-Angular with MIT License | 5 votes |
@Bean(name = "transactionManager") public HibernateTransactionManager getTransactionManager( SessionFactory sessionFactory) { HibernateTransactionManager transactionManager = new HibernateTransactionManager( sessionFactory); return transactionManager; }
Example #13
Source File: EntityManagerFactoryBuilderImpl.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void sessionFactoryClosed(SessionFactory sessionFactory) { SessionFactoryImplementor sfi = ( (SessionFactoryImplementor) sessionFactory ); sfi.getServiceRegistry().destroy(); ServiceRegistry basicRegistry = sfi.getServiceRegistry().getParentServiceRegistry(); ( (ServiceRegistryImplementor) basicRegistry ).destroy(); }
Example #14
Source File: SFLocalContext.java From sailfish-core with Apache License 2.0 | 5 votes |
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 #15
Source File: HibernateL2CacheSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** * 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 #16
Source File: ExternalDataSourceConnectionProviderTest.java From hibernate-master-class with Apache License 2.0 | 5 votes |
@Override protected SessionFactory newSessionFactory() { Properties properties = getProperties(); return new Configuration() .addProperties(properties) .addAnnotatedClass(SecurityId.class) .buildSessionFactory( new StandardServiceRegistryBuilder() .applySettings(properties) .build() ); }
Example #17
Source File: HibernateDaoIntegrationTests.java From judgels with GNU General Public License v2.0 | 5 votes |
@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 #18
Source File: SqlReportEntitiesPersister.java From aw-reporting with Apache License 2.0 | 5 votes |
/** * 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 #19
Source File: HibernateUtil.java From maven-framework-project with MIT License | 5 votes |
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 #20
Source File: SessionFactoryRegistry.java From lams with GNU General Public License v2.0 | 5 votes |
public SessionFactory findSessionFactory(String uuid, String name) { SessionFactory sessionFactory = getSessionFactory( uuid ); if ( sessionFactory == null && StringHelper.isNotEmpty( name ) ) { sessionFactory = getNamedSessionFactory( name ); } return sessionFactory; }
Example #21
Source File: LocalSessionFactoryBeanTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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 #22
Source File: ManagedSessionContext.java From lams with GNU General Public License v2.0 | 5 votes |
/** * 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 #23
Source File: SessionFactoryUtils.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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 #24
Source File: StatisticsTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
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); }
Example #25
Source File: HibernateIdentifiableObjectStore.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
public HibernateIdentifiableObjectStore( SessionFactory sessionFactory, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, Class<T> clazz, CurrentUserService currentUserService, AclService aclService, boolean cacheable ) { super( sessionFactory, jdbcTemplate, publisher, clazz, cacheable ); checkNotNull( currentUserService ); checkNotNull( aclService ); this.currentUserService = currentUserService; this.aclService = aclService; this.cacheable = cacheable; }
Example #26
Source File: HibernateSimple.java From java-course-ee with MIT License | 5 votes |
public static void main(String[] args) { HibernateSimple hs = new HibernateSimple(); SessionFactory sf = hs.getSessionFactory(); Session s = sf.getCurrentSession(); s.beginTransaction(); // Получить список через SQL-запрос List<Region> regionList = s.createQuery("from Region").list(); for (Region r : regionList) { System.out.println(r); } // Добавить через SQL-запрос Region newRegion = new Region(); newRegion.setRegionName("Simple Region"); Serializable id = s.save(newRegion); // Изменить через SQL-запрос regionList.get(0).setRegionName("Other Region"); s = restartSession(s, sf); // Загрузить через SQL-запрос //Region load = (Region) s.get(Region.class, id); Region load = (Region) s.load(Region.class, id); // Удалить через SQL-запрос s.delete(load); s.getTransaction().commit(); }
Example #27
Source File: LocalSessionFactoryBeanTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithDataSourceAndMappingJarLocations() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); final Set invocations = new HashSet(); LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @Override protected Configuration newConfiguration() { return new Configuration() { @Override public Configuration addJar(File file) { invocations.add("addResource " + file.getPath()); return this; } }; } @Override protected SessionFactory newSessionFactory(Configuration config) { assertEquals(LocalDataSourceConnectionProvider.class.getName(), config.getProperty(Environment.CONNECTION_PROVIDER)); assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource()); invocations.add("newSessionFactory"); return null; } }; sfb.setMappingJarLocations(new Resource[]{ new FileSystemResource("mapping.hbm.jar"), new FileSystemResource("mapping2.hbm.jar")}); sfb.setDataSource(ds); sfb.afterPropertiesSet(); assertTrue(sfb.getConfiguration() != null); assertTrue(invocations.contains("addResource mapping.hbm.jar")); assertTrue(invocations.contains("addResource mapping2.hbm.jar")); assertTrue(invocations.contains("newSessionFactory")); }
Example #28
Source File: HibernateJpaSessionFactoryBean.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override 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 #29
Source File: HibernateSimple.java From java-course-ee with MIT License | 5 votes |
public static void main(String[] args) { HibernateSimple hs = new HibernateSimple(); SessionFactory sessionFactory = hs.getSessionFactory(); for (int i = 0; i < 3000; i++) { MyThread m = new MyThread(sessionFactory); m.start(); } }
Example #30
Source File: AbstractHibernateDatastore.java From gorm-hibernate5 with Apache License 2.0 | 5 votes |
@Override public <T1> T1 withNewSession(Serializable tenantId, Closure<T1> callable) { if(getMultiTenancyMode() == MultiTenancySettings.MultiTenancyMode.DATABASE) { AbstractHibernateDatastore datastore = getDatastoreForConnection(tenantId.toString()); SessionFactory sessionFactory = datastore.getSessionFactory(); return datastore.getHibernateTemplate().executeWithExistingOrCreateNewSession( sessionFactory, callable); } else { return withNewSession(callable); } }