org.hibernate.SessionFactory类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(128)

本文整理了Java中org.hibernate.SessionFactory类的一些代码示例,展示了SessionFactory类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SessionFactory类的具体详情如下:
包路径:org.hibernate.SessionFactory
类名称:SessionFactory

SessionFactory介绍

[英]The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.

Implementors must be threadsafe.
[中]这里的主要约定是创建会话实例。通常,应用程序只有一个SessionFactory实例,为客户端请求提供服务的线程从该工厂获取会话实例。
SessionFactory的内部状态是不变的。一旦它被创建,这个内部状态就会被设置。这个内部状态包括关于对象/关系映射的所有元数据。
实现者必须是线程安全的。

代码示例

代码示例来源:origin: hibernate/hibernate-orm

/**
 * Call setEntity() on a cacheable query - see FORGE-265
 */
public List listEventsOfOrganizer(Person organizer) {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  Query query = session.createQuery("from Event ev where ev.organizer = :organizer");
  query.setCacheable(true);
  query.setEntity("organizer", organizer);
  List result = query.list();
  session.getTransaction().commit();
  return result;
}

代码示例来源: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: spring-projects/spring-framework

@Override
public void destroy() {
  if (this.sessionFactory != null) {
    this.sessionFactory.close();
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@TestForIssue(jiraKey = "HHH-4838")
@Test
public void testNaturalKeyLookupWithConstraint() {
  Session s = openSession();
  Transaction newTx = s.getTransaction();
  newTx.begin();
  A a1 = new A();
  a1.setName( "name1" );
  s.persist( a1 );
  newTx.commit();
  newTx = s.beginTransaction();
  getCriteria( s ).add( Restrictions.isNull( "singleD" ) ).uniqueResult(); // put query-result into cache
  A a2 = new A();
  a2.setName( "xxxxxx" );
  s.persist( a2 );
  newTx.commit();	  // Invalidates space A in UpdateTimeStamps region
  newTx = s.beginTransaction();
  Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() );
  s.getSessionFactory().getStatistics().clear();
  // should not produce a hit in StandardQuery cache region because there is a constraint
  getCriteria( s ).add( Restrictions.isNull( "singleD" ) ).uniqueResult();
  Assert.assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() );
  s.createQuery( "delete from A" ).executeUpdate();
  newTx.commit();
  // Shutting down the application
  s.close();
}

代码示例来源: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: hibernate/hibernate-orm

/**
 * Use a Criteria query - see FORGE-247
 */
public List listEventsWithCriteria() {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  List result = session.createCriteria(Event.class)
    .setCacheable(true)
    .list();
  session.getTransaction().commit();
  return result;
}

代码示例来源:origin: org.ikasan/ikasan-connector-basefiletransfer

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());
  query.setMaxResults(maxRows);
  fileFilters = query.list();
  if (fileFilters != null)
      session.delete(fileFilter);
      session.flush();
  sb.append(hibernateQuery.toString());
  sb.append("].");
  logger.error(sb.toString() + " " + e.getMessage(), e);
  throw e;

代码示例来源:origin: hibernate/hibernate-orm

public Long createAndStorePerson(Person person) {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  Long personId = (Long)session.save(person);
  session.getTransaction().commit();
  return personId;
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see org.openmrs.api.db.ConceptDAO#getConceptReferenceTermsBySource(ConceptSource)
 */
@SuppressWarnings("unchecked")
@Override
public List<ConceptReferenceTerm> getConceptReferenceTermsBySource(ConceptSource conceptSource) throws DAOException {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptReferenceTerm.class);
  criteria.add(Restrictions.eq("conceptSource", conceptSource));
  return (List<ConceptReferenceTerm>) criteria.list();
}

代码示例来源:origin: gocd/gocd

@Override
  public Object doInTransaction(TransactionStatus transactionStatus) {
    return sessionFactory.getCurrentSession()
        .createCriteria(PipelineState.class)
        .add(Restrictions.eq("pipelineName", pipelineName))
        .setCacheable(false).uniqueResult();
  }
});

代码示例来源:origin: vatri/spring-rest-ecommerce

public String addProductImage(final String productId, final String filename){
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  ProductImage image = new ProductImage();
  image.setProductId(Long.parseLong(productId));
  image.setPath(filename);
  try {
    String res = session.save(image).toString();
    session.getTransaction().commit();
    return res;
  } catch (HibernateException e) {
    System.out.print(e.getMessage());
    session.getTransaction().rollback();
  } finally {
    session.close();
  }
  return "";
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see org.openmrs.hl7.db.HL7DAO#getAllHL7InQueues()
 */
@Override
@SuppressWarnings("unchecked")
public List<HL7InQueue> getAllHL7InQueues() throws DAOException {
  return sessionFactory.getCurrentSession()
      .createQuery("from HL7InQueue where messageState = ? order by HL7InQueueId").setParameter(0,
        HL7Constants.HL7_STATUS_PENDING, StandardBasicTypes.INTEGER).list();
}

代码示例来源:origin: gocd/gocd

@Override
  public Object doInTransaction(TransactionStatus status) {
    PropertyProjection pipelineName = Projections.property("pipelineName");
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PipelineState.class).setProjection(pipelineName).add(
        Restrictions.eq("locked", true));
    criteria.setCacheable(false);
    List<String> list = criteria.list();
    return list;
  }
});

代码示例来源:origin: openmrs/openmrs-core

public boolean isOrderFrequencyInUse(OrderFrequency orderFrequency) {
  Map<String, ClassMetadata> metadata = sessionFactory.getAllClassMetadata();
  for (ClassMetadata classMetadata : metadata.values()) {
    Class<?> entityClass = classMetadata.getMappedClass();
    for (String name : names) {
      if (classMetadata.getPropertyType(name).getReturnedClass().equals(OrderFrequency.class)) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
        criteria.add(Restrictions.eq(name, orderFrequency));
        criteria.setMaxResults(1);
        if (!criteria.list().isEmpty()) {
          return true;

代码示例来源:origin: gocd/gocd

public EnvironmentVariables load(final Long entityId, final EnvironmentVariableType type) {
  List<EnvironmentVariable> result = (List<EnvironmentVariable>) transactionTemplate.execute((TransactionCallback) transactionStatus -> {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(EnvironmentVariable.class).add(Restrictions.eq("entityId", entityId)).add(
        Restrictions.eq("entityType", type.toString())).addOrder(Order.asc("id"));
    criteria.setCacheable(true);
    return criteria.list();
  });
  return new EnvironmentVariables(result);
}

代码示例来源:origin: hibernate/hibernate-orm

public void addPhoneNumberToPerson(Long personId, PhoneNumber pN) {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  Person aPerson = (Person)session.load(Person.class, personId);
  pN.setPersonId(personId.longValue());
  aPerson.getPhoneNumbers().add(pN);
  session.getTransaction().commit();
}

代码示例来源:origin: gocd/gocd

public Users findNotificationSubscribingUsers() {
  return (Users) transactionTemplate.execute((TransactionCallback) transactionStatus -> {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class);
    criteria.setCacheable(true);
    criteria.add(Restrictions.isNotEmpty("notificationFilters"));
    criteria.add(Restrictions.eq("enabled", true));
    return new Users(criteria.list());
  });
}

代码示例来源: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: org.ikasan/ikasan-connector-basefiletransfer

FileFilter resultObject = null;
Session session = this.sessionFactory.openSession();
try
  Query query = session.createQuery(hibernateQuery.toString());
  query.setParameter(CLIENT_ID, qo.getClientId());
  if (filterOnFilename)
    query.setParameter(CRITERIA, qo.getCriteria());
    query.setParameter(LAST_MODIFIED, qo.getLastModified());
  query.setParameter(SIZE, qo.getSize());
  sb.append(hibernateQuery.toString());
  sb.append("]."); //$NON-NLS-1$
  logger.error(sb.toString() + " " + e.getMessage(), e); //$NON-NLS-1$
  throw e;
  if (session.isOpen())
    session.close();

代码示例来源:origin: hibernate/hibernate-orm

@Test
  public void testExplicitClassReturn() {
    Session session = sf.openSession();
    session.beginTransaction();

    ProcedureCall call = session.createStoredProcedureCall( "all_items", Item.class );
    call.registerParameter( 1, void.class, ParameterMode.REF_CURSOR );
    ProcedureOutputs outputs = call.getOutputs();
    ResultSetOutput results = assertTyping( ResultSetOutput.class, outputs.getCurrent() );

    session.getTransaction().commit();
    session.close();
  }
}

相关文章