Java Code Examples for org.hibernate.SessionFactory#openSession()
The following examples show how to use
org.hibernate.SessionFactory#openSession() .
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: Main.java From maven-framework-project with MIT License | 6 votes |
private static List list() { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); List employees = session.createQuery("from Employee").list(); session.close(); return employees; }
Example 2
Source File: PortfolioManager.java From crypto-bot with Apache License 2.0 | 6 votes |
/** * Write the USD portfolio value to DB * @throws APIException */ private void updatePortfolioValue() throws APIException { logger.debug("Updating portfolio value"); final BigDecimal portfolioValueUSD = getTotalPortfolioValueInUSD(); final PortfolioValue portfolioValue = new PortfolioValue(); portfolioValue.setApikey(bitfinexApiBroker.getApiKey()); portfolioValue.setUsdValue(portfolioValueUSD); final SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); try(final Session session = sessionFactory.openSession()) { session.beginTransaction(); session.save(portfolioValue); session.getTransaction().commit(); } }
Example 3
Source File: HibernateSampleApplication.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Main method that runs a simple console application that saves a {@link Person} entity and then * retrieves it to print to the console. */ public static void main(String[] args) { // Create Hibernate environment objects. StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() .build(); SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata() .buildSessionFactory(); Session session = sessionFactory.openSession(); // Save an entity into Spanner Table. savePerson(session); session.close(); }
Example 4
Source File: HibernateLifecycleUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void whenReattached_thenTrackedAgain() throws Exception { SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); try (Session session = sessionFactory.openSession()) { Transaction transaction = startTransaction(session); FootballPlayer messi = session.get(FootballPlayer.class, 2L); session.evict(messi); messi.setName("Leo Messi"); transaction.commit(); assertThat(getDirtyEntities()).isEmpty(); transaction = startTransaction(session); session.update(messi); transaction.commit(); assertThat(getDirtyEntities()).size().isEqualTo(1); assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Leo Messi"); } }
Example 5
Source File: TransactionsTest.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void jdbc() { //tag::transactions-api-jdbc-example[] StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() // "jdbc" is the default, but for explicitness .applySetting( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jdbc" ) .build(); Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( Customer.class ) .getMetadataBuilder() .build(); SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() .build(); Session session = sessionFactory.openSession(); try { // calls Connection#setAutoCommit( false ) to // signal start of transaction session.getTransaction().begin(); session.createQuery( "UPDATE customer set NAME = 'Sir. '||NAME" ) .executeUpdate(); // calls Connection#commit(), if an error // happens we attempt a rollback session.getTransaction().commit(); } catch ( Exception e ) { // we may need to rollback depending on // where the exception happened if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) { session.getTransaction().rollback(); } // handle the underlying error } finally { session.close(); sessionFactory.close(); } //end::transactions-api-jdbc-example[] }
Example 6
Source File: ConfigurationPerformanceTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public void xtestSessionFactoryCreationTime() throws FileNotFoundException, IOException, ClassNotFoundException { File perfs = new File("perfsrc"); generateTestFiles(perfs, "perftest"); if(perfs.exists()) { SessionFactory factory = saveAndLoad("perfsrc/perftest/", new File(perfs, "perftest").list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".hbm.xml"); } }), "hibernateperftest.cfg.bin"); Session session = factory.openSession(); Object o = session.load("perftest.Test1", new Long(42)); System.out.println(o); } else { System.err.println(perfs.getAbsoluteFile() + " not found"); } }
Example 7
Source File: Main.java From chuidiang-ejemplos with GNU Lesser General Public License v3.0 | 6 votes |
private static void updateGeometry(SessionFactory sessionFactory) { Session session = sessionFactory.openSession(); session.beginTransaction(); TheData theData = session.get(TheData.class, 1L); LineString geometry = geometryFactory.createLineString(new Coordinate[]{ new Coordinate(5,6), new Coordinate(7,8), new Coordinate(9,10)}); theData.setTheGeometry(geometry); session.saveOrUpdate(theData); session.getTransaction().commit(); session.close(); }
Example 8
Source File: HibernateTest.java From java-jdbc with Apache License 2.0 | 6 votes |
@Test public void hibernate_with_ignored_statement() { SessionFactory sessionFactory = createSessionFactory(false, Collections.singletonList("insert into Employee (id) values (?)")); Session session = sessionFactory.openSession(); Employee employee = new Employee(); session.beginTransaction(); session.save(employee); session.getTransaction().commit(); session.close(); sessionFactory.close(); assertNotNull(employee.id); List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertEquals(8, finishedSpans.size()); checkSpans(finishedSpans, "hibernate"); assertNull(mockTracer.activeSpan()); }
Example 9
Source File: TestBack.java From LibrarySystem with Apache License 2.0 | 5 votes |
@Test public void testGetBack(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); BackInfo back = (BackInfo) session.get(BackInfo.class, 4); System.out.println(back); session.close(); }
Example 10
Source File: TestBookType.java From LibrarySystem with Apache License 2.0 | 5 votes |
@Test public void testDeleteBookType(){ SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); BookType booktype = (BookType) session.get(BookType.class, 1); session.delete(booktype); transaction.commit(); session.close(); }
Example 11
Source File: HibernateTest.java From Oceanus with Apache License 2.0 | 5 votes |
@Test public void selectTest() throws SQLException{ SessionFactory sf = conf.buildSessionFactory(); for(long id=1; id<99; id++){ Session session = sf.openSession(); User user = (User) session.get(User.class, Long.valueOf(id)); System.out.println(user); session.close(); } }
Example 12
Source File: ValueGenerationDemo.java From HibernateDemos with The Unlicense | 5 votes |
public static void main(String[] args) { final Configuration configuration = new Configuration(); configuration.addAnnotatedClass( Project.class ); // necessary for a known bug, to be fixed in 4.2.9.Final configuration.setProperty( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); final SessionFactory sessionFactory = configuration.buildSessionFactory( new StandardServiceRegistryBuilder().build() ); Session s = sessionFactory.openSession(); final Project project = new Project(); s.getTransaction().begin(); s.persist(project); s.getTransaction().commit(); s.clear(); System.out.println(project.toString()); s.getTransaction().begin(); s.update(project ); s.getTransaction().commit(); s.close(); System.out.println(project.toString()); System.exit(0); }
Example 13
Source File: Main.java From maven-framework-project with MIT License | 5 votes |
private static List list() { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); List employees = session.createQuery("from Employee").list(); session.close(); return employees; }
Example 14
Source File: OpenSessionInViewFilter.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Open a Session for the SessionFactory that this filter uses. * <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 that this filter uses * @return the Session to use * @throws DataAccessResourceFailureException if the Session could not be created * @see FlushMode#MANUAL */ protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { try { Session session = sessionFactory.openSession(); session.setFlushMode(FlushMode.MANUAL); return session; } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
Example 15
Source File: BasePaymentModuleDBTestCase.java From yes-cart with Apache License 2.0 | 5 votes |
@Override protected void before() throws Throwable { ctx = createContext(); sessionFactory = (SessionFactory) ctx().getBean("paySessionFactory"); session = sessionFactory.openSession(); dbTester = createDatabaseTester(); dbTester.onSetup(); }
Example 16
Source File: EmployeeHandler.java From lambda-rds-mysql with Apache License 2.0 | 5 votes |
@Override public String handleRequest(Request request, Context context) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); try (Session session = sessionFactory.openSession()) { session.beginTransaction(); Employee employee = new Employee(); employee.setId(request.id); employee.setName(request.name); session.save(employee); session.getTransaction().commit(); } return String.format("Added %s %s.", request.id, request.name); }
Example 17
Source File: StatsTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
public void testCollectionFetchVsLoad() throws Exception { Statistics stats = getSessions().getStatistics(); stats.clear(); Session s = openSession(); Transaction tx = s.beginTransaction(); Continent europe = fillDb(s); tx.commit(); s.clear(); tx = s.beginTransaction(); assertEquals(0, stats.getCollectionLoadCount() ); assertEquals(0, stats.getCollectionFetchCount() ); Continent europe2 = (Continent) s.get( Continent.class, europe.getId() ); assertEquals("Lazy true: no collection should be loaded", 0, stats.getCollectionLoadCount() ); assertEquals( 0, stats.getCollectionFetchCount() ); europe2.getCountries().size(); assertEquals( 1, stats.getCollectionLoadCount() ); assertEquals("Explicit fetch of the collection state", 1, stats.getCollectionFetchCount() ); tx.commit(); s.close(); s = openSession(); tx = s.beginTransaction(); stats.clear(); europe = fillDb(s); tx.commit(); s.clear(); tx = s.beginTransaction(); assertEquals( 0, stats.getCollectionLoadCount() ); assertEquals( 0, stats.getCollectionFetchCount() ); europe2 = (Continent) s.createQuery( "from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId() ).uniqueResult(); assertEquals( 1, stats.getCollectionLoadCount() ); assertEquals( "collection should be loaded in the same query as its parent", 0, stats.getCollectionFetchCount() ); tx.commit(); s.close(); Collection coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries"); coll.setFetchMode(FetchMode.JOIN); coll.setLazy(false); SessionFactory sf = getCfg().buildSessionFactory(); stats = sf.getStatistics(); stats.clear(); stats.setStatisticsEnabled(true); s = sf.openSession(); tx = s.beginTransaction(); europe = fillDb(s); tx.commit(); s.clear(); tx = s.beginTransaction(); assertEquals( 0, stats.getCollectionLoadCount() ); assertEquals( 0, stats.getCollectionFetchCount() ); europe2 = (Continent) s.get( Continent.class, europe.getId() ); assertEquals( 1, stats.getCollectionLoadCount() ); assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, stats.getCollectionFetchCount() ); tx.commit(); s.close(); sf.close(); coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries"); coll.setFetchMode(FetchMode.SELECT); coll.setLazy(false); sf = getCfg().buildSessionFactory(); stats = sf.getStatistics(); stats.clear(); stats.setStatisticsEnabled(true); s = sf.openSession(); tx = s.beginTransaction(); europe = fillDb(s); tx.commit(); s.clear(); tx = s.beginTransaction(); assertEquals( 0, stats.getCollectionLoadCount() ); assertEquals( 0, stats.getCollectionFetchCount() ); europe2 = (Continent) s.get( Continent.class, europe.getId() ); assertEquals( 1, stats.getCollectionLoadCount() ); assertEquals( "Should do explicit collection load, not part of the first one", 1, stats.getCollectionFetchCount() ); Iterator countries = europe2.getCountries().iterator(); while ( countries.hasNext() ) { s.delete( countries.next() ); } cleanDb( s ); tx.commit(); s.close(); }
Example 18
Source File: ProductsDAO.java From primefaces-blueprints with The Unlicense | 4 votes |
private Session getSession() { SessionFactory sf = HibernateUtil.getSessionFactory(); return sf.isClosed() ? sf.openSession() : sf.getCurrentSession(); }
Example 19
Source File: Main.java From maven-framework-project with MIT License | 3 votes |
private static Employee update(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.merge(employee); session.getTransaction().commit(); session.close(); return employee; }
Example 20
Source File: Main.java From maven-framework-project with MIT License | 3 votes |
private static void delete(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.delete(employee); session.getTransaction().commit(); session.close(); }