下面列出了org.hibernate.SessionFactory#openSession ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
@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");
}
}
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();
}
@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());
}
@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);
}
@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);
}
}
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);
}
@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();
}
}
private static List list() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List employees = session.createQuery("from Employee").list();
session.close();
return employees;
}
@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();
}
@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();
}
private static List list() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List employees = session.createQuery("from Employee").list();
session.close();
return employees;
}
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[]
}
private Session getSession() {
SessionFactory sf = HibernateUtil.getSessionFactory();
return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
}
private static void delete(Employee employee) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.delete(employee);
session.getTransaction().commit();
session.close();
}
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;
}