org.hibernate.SessionFactory#openSession ( )源码实例Demo

下面列出了org.hibernate.SessionFactory#openSession ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: crypto-bot   文件: PortfolioManager.java
/**
 * 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();
	}
}
 
/**
 * 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();
}
 
源代码3 项目: tutorials   文件: HibernateLifecycleUnitTest.java
@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");
    }
}
 
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");
	}
}
 
源代码5 项目: chuidiang-ejemplos   文件: Main.java
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();
}
 
源代码6 项目: java-jdbc   文件: HibernateTest.java
@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());
}
 
源代码7 项目: lambda-rds-mysql   文件: EmployeeHandler.java
@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);
}
 
源代码8 项目: yes-cart   文件: BasePaymentModuleDBTestCase.java
@Override
protected void before() throws Throwable {
    ctx = createContext();
    sessionFactory = (SessionFactory) ctx().getBean("paySessionFactory");
    session = sessionFactory.openSession();
    dbTester = createDatabaseTester();
    dbTester.onSetup();
}
 
/**
 * 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);
	}
}
 
源代码10 项目: HibernateDemos   文件: ValueGenerationDemo.java
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);
}
 
源代码11 项目: Oceanus   文件: HibernateTest.java
@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();
	}
}
 
源代码12 项目: maven-framework-project   文件: Main.java
private static List list() {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	List employees = session.createQuery("from Employee").list();
	session.close();
	return employees;
}
 
源代码13 项目: LibrarySystem   文件: TestBack.java
@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();
}
 
源代码14 项目: LibrarySystem   文件: TestBookType.java
@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();

}
 
源代码15 项目: maven-framework-project   文件: Main.java
private static List list() {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	List employees = session.createQuery("from Employee").list();
	session.close();
	return employees;
}
 
源代码16 项目: cacheonix-core   文件: StatsTest.java
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();
}
 
@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[]
}
 
源代码18 项目: primefaces-blueprints   文件: ProductsDAO.java
private Session getSession() {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
}
 
源代码19 项目: maven-framework-project   文件: Main.java
private static void delete(Employee employee) {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();
	
	session.beginTransaction();
	
	session.delete(employee);
	
	session.getTransaction().commit();
	
	session.close();
}
 
源代码20 项目: maven-framework-project   文件: Main.java
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;

}