本文整理了Java中org.hibernate.SessionFactory.openSession()
方法的一些代码示例,展示了SessionFactory.openSession()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SessionFactory.openSession()
方法的具体详情如下:
包路径:org.hibernate.SessionFactory
类名称:SessionFactory
方法名:openSession
[英]Open a Session.
JDBC Connection will be obtained from the configured org.hibernate.engine.jdbc.connections.spi.ConnectionProvider as needed to perform requested work.
[中]开个会。
JDBC连接将从配置的组织获得。冬眠发动机jdbc。连接。spi。执行请求的工作所需的ConnectionProvider。
代码示例来源:origin: iluwatar/java-design-patterns
@Override
public Spell findByName(String name) {
Transaction tx = null;
Spell result = null;
try (Session session = getSessionFactory().openSession()) {
tx = session.beginTransaction();
Criteria criteria = session.createCriteria(persistentClass);
criteria.add(Restrictions.eq("name", name));
result = (Spell) criteria.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
return result;
}
}
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void testDeclarativeMix() throws Exception {
Configuration cfg = new Configuration();
cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
SessionFactory sf = cfg.buildSessionFactory();
assertNotNull( sf );
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
Query q = s.createQuery( "from Boat" );
assertEquals( 0, q.list().size() );
q = s.createQuery( "from Plane" );
assertEquals( 0, q.list().size() );
tx.commit();
s.close();
sf.close();
}
@Test
代码示例来源:origin: spring-projects/spring-batch
statefulSession = sessionFactory.openSession();
return statefulSession.createQuery(queryString);
代码示例来源:origin: openmrs/openmrs-core
@Override
public void openSession() {
log.debug("HibernateContext: Opening Hibernate Session");
if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
if (log.isDebugEnabled()) {
log.debug("Participating in existing session (" + sessionFactory.hashCode() + ")");
}
participate = true;
} else {
if (log.isDebugEnabled()) {
log.debug("Registering session with synchronization manager (" + sessionFactory.hashCode() + ")");
}
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
}
代码示例来源:origin: com.manydesigns/portofino-database
public Session getThreadSession(boolean create) {
Session session = threadSessions.get();
if(session == null && create) {
if(logger.isDebugEnabled()) {
logger.debug("Creating thread-local session for {}", Thread.currentThread());
}
session = sessionFactory.openSession();
session.beginTransaction();
threadSessions.set(session);
}
return session;
}
代码示例来源:origin: phenotips/phenotips
@Override
public void deletePatientPushInfo(String localPatientID)
{
if (localPatientID == null) {
return;
}
Session session = this.sessionFactory.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
t.begin();
Query query = session.createQuery(HQL_DELETE_ALL_PUSH_HISTRY_FOR_LOCAL_PATIENT);
query.setParameter("localId", localPatientID);
int numDeleted = query.executeUpdate();
this.logger.debug("Removed all [{}] stored push history records for local patient with ID [{}]",
numDeleted, localPatientID);
t.commit();
}
代码示例来源:origin: org.ikasan/ikasan-connector-basefiletransfer
logger.debug("About to housekeep by running [" + hibernateQuery
+ "], where clientId [" + clientId
+ "], createdDateTime [" + cal.getTime().getTime()
Session session = this.sessionFactory.openSession();
try
Query query = session.createQuery(hibernateQuery.toString());
query.setParameter(CLIENT_ID, clientId);
query.setParameter(CREATED_DATE_TIME, cal.getTime().getTime());
sb.append(hibernateQuery.toString());
sb.append("].");
logger.error(sb.toString() + " " + e.getMessage(), e);
throw e;
代码示例来源:origin: org.sakaiproject.samigo/samigo-services
Session session = null;
try {
session = getSessionFactory().openSession();
String query0 = "select LOCATION from SAM_MEDIA_T where MEDIAID = :id";
mediaLocation = (String) session.createSQLQuery(query0).setLong("id", mediaId).uniqueResult();
log.debug("****mediaLocation=" + mediaLocation);
log.warn(e.getMessage());
} finally {
if (session != null) {
代码示例来源:origin: hibernate/hibernate-orm
Session s = sf.openSession();
s.getTransaction().begin();
EntityWithConvertibleField entity = new EntityWithConvertibleField();
s.close();
s = sf.openSession();
s.beginTransaction();
entity = (EntityWithConvertibleField) s.load( EntityWithConvertibleField.class, entityID );
assertEquals( ConvertibleEnum.VALUE, entity.getConvertibleEnum() );
s.getTransaction().commit();
assertEquals( "'VALUE'", outcome );
s = sf.openSession();
s.beginTransaction();
s.createQuery( "FROM EntityWithConvertibleField e where e.convertibleEnum = org.hibernate.test.converter.AttributeConverterTest$ConvertibleEnum.VALUE" )
.list();
s.getTransaction().commit();
s.close();
s = sf.openSession();
s.beginTransaction();
s.delete( entity );
s.getTransaction().commit();
代码示例来源:origin: hibernate/hibernate-ogm
public static void delete(SessionFactory sessions, Class<?> entityClass, Serializable... ids) {
final Session session = sessions.openSession();
Transaction transaction = session.beginTransaction();
for ( Serializable id : ids ) {
session.delete( session.load( entityClass, id ) );
}
transaction.commit();
session.close();
}
代码示例来源:origin: Transitime/core
Session session = sessionFactory.openSession();
Query query = session.createQuery(hql);
} catch (HibernateException e) {
logger.error(e.getMessage(), e);
return null;
} finally {
代码示例来源:origin: phenotips/phenotips
@Override
public void store(AuditEvent event)
{
if (ACTION_IGNORED.contains(event.getAction())) {
return;
}
Session session = this.sessionFactory.getSessionFactory().openSession();
try {
Transaction t = session.beginTransaction();
t.begin();
session.save(event);
t.commit();
} catch (HibernateException ex) {
this.logger.error("Failed to save audit event [{}]: {}", event, ex.getMessage(), ex);
} finally {
session.close();
}
}
代码示例来源:origin: com.opensymphony.propertyset.providers/hibernate4
public void remove(String entityName, Long entityId, String key)
{
Session session = null;
try
{
session = this.sessionFactory.openSession();
session.delete(HibernatePropertySetDAOUtils.getItem(session, entityName, entityId, key));
session.flush();
}
catch (HibernateException e)
{
throw new PropertyException("Could not remove key '" + key + "': " + e.getMessage());
}
finally
{
try
{
if (session != null)
{
session.close();
}
}
catch (Exception e)
{
}
}
}
}
代码示例来源:origin: com.atlassian.crowd/crowd-persistence-hibernate5
@Override
protected Session openSession() {
if (currentSessionHolder.get() != null) {
throw new IllegalStateException("session already open");
}
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
session.setCacheMode(CacheMode.IGNORE);
currentSessionHolder.set(session);
log.debug("open new session [{}]", currentSessionHolder.get());
return session;
}
}
代码示例来源:origin: ManyDesigns/Portofino
public Session getThreadSession(boolean create) {
Session session = threadSessions.get();
if(session == null && create) {
if(logger.isDebugEnabled()) {
logger.debug("Creating thread-local session for {}", Thread.currentThread());
}
session = sessionFactory.openSession();
session.beginTransaction();
threadSessions.set(session);
}
return session;
}
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void testHbmWithSubclassExtends() throws Exception {
Configuration cfg = new Configuration();
cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
cfg.addClass( Ferry.class );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
SessionFactory sf = cfg.buildSessionFactory();
assertNotNull( sf );
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
Query q = s.createQuery( "from Ferry" );
assertEquals( 0, q.list().size() );
q = s.createQuery( "from Plane" );
assertEquals( 0, q.list().size() );
tx.commit();
s.close();
sf.close();
}
@Test
代码示例来源:origin: spring-projects/spring-batch
@Test
@SuppressWarnings("unchecked")
public void testStatefulClose(){
SessionFactory sessionFactory = mock(SessionFactory.class);
Session session = mock(Session.class);
Query<Foo> scrollableResults = mock(Query.class);
HibernateCursorItemReader<Foo> itemReader = new HibernateCursorItemReader<>();
itemReader.setSessionFactory(sessionFactory);
itemReader.setQueryString("testQuery");
itemReader.setUseStatelessSession(false);
when(sessionFactory.openSession()).thenReturn(session);
when(session.createQuery("testQuery")).thenReturn(scrollableResults);
when(scrollableResults.setFetchSize(0)).thenReturn(scrollableResults);
itemReader.open(new ExecutionContext());
itemReader.close();
}
代码示例来源:origin: dropwizard/dropwizard
@Override
protected Result check() throws Exception {
return timeBoundHealthCheck.check(() -> {
try (Session session = sessionFactory.openSession()) {
final Transaction txn = session.beginTransaction();
try {
session.createNativeQuery(validationQuery).list();
txn.commit();
} catch (Exception e) {
if (txn.getStatus().canRollback()) {
txn.rollback();
}
throw e;
}
}
return Result.healthy();
});
}
}
代码示例来源:origin: hibernate/hibernate-tools
Session session = sf.openSession();
Transaction t = session.beginTransaction();
session.close();
session = sf.openSession();
t = session.beginTransaction();
session.close();
session = sf.openSession();
t = session.beginTransaction();
order = (Orders) session.load(Orders.class, Integer.valueOf(1) );
Assert.assertFalse(Hibernate.isInitialized(order) );
Assert.assertFalse(Hibernate.isInitialized(order.getItemsForOrderId() ) );
order = (Orders) session.createQuery("from " + PACKAGE_NAME + ".Orders").getSingleResult();
代码示例来源:origin: david-schuler/javalanche
/**
* Removes the mutations that have a result from the given list of
* mutations.
*
* @param mutations
* the list of mutations to be filtered.
*/
private static void filterMutationsWithResult(List<Mutation> mutations) {
if (mutations != null) {
// make sure that we have not got any mutations that have already an
// result
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
List<Mutation> toRemove = new ArrayList<Mutation>();
for (Mutation m : mutations) {
session.load(m, m.getId());
if (m.getMutationResult() != null) {
logger.debug("Found mutation that already has a mutation result "
+ m);
toRemove.add(m);
}
}
mutations.removeAll(toRemove);
tx.commit();
session.close();
}
}
内容来源于网络,如有侵权,请联系作者删除!