下面列出了怎么用org.hibernate.SessionFactory的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) {
String path = "hibernate.cfg.xml";
Configuration cfg = new Configuration().configure(path);
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
User user = new User();
user.setId("443");
user.setName("baa");
session.save(user);
// session.close();
session.getTransaction().commit();
sessionFactory.close();
}
@Test
public void givenTransientEntity_whenSave_thenManaged() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
FootballPlayer neymar = new FootballPlayer();
neymar.setName("Neymar");
session.save(neymar);
assertThat(getManagedEntities(session)).size().isEqualTo(1);
assertThat(neymar.getId()).isNotNull();
int count = queryCount("select count(*) from Football_Player where name='Neymar'");
assertThat(count).isEqualTo(0);
transaction.commit();
count = queryCount("select count(*) from Football_Player where name='Neymar'");
assertThat(count).isEqualTo(1);
transaction = startTransaction(session);
session.delete(neymar);
transaction.commit();
}
}
/**
* @param sesFactory Session factory.
* @param idToChildCnt Number of children per entity.
* @param expHit Expected cache hits.
* @param expMiss Expected cache misses.
*/
@SuppressWarnings("unchecked")
private void assertCollectionCache(SessionFactory sesFactory, Map<Integer, Integer> idToChildCnt, int expHit,
int expMiss) {
sesFactory.getStatistics().clear();
Session ses = sesFactory.openSession();
try {
for (Map.Entry<Integer, Integer> e : idToChildCnt.entrySet()) {
Entity entity = (Entity)ses.load(Entity.class, e.getKey());
assertEquals((int)e.getValue(), entity.getChildren().size());
}
}
finally {
ses.close();
}
SecondLevelCacheStatistics stats =
sesFactory.getStatistics().getSecondLevelCacheStatistics(CHILD_COLLECTION_REGION);
assertEquals(expHit, stats.getHitCount());
assertEquals(expMiss, stats.getMissCount());
}
private static SessionFactory locateSessionFactoryOnDeserialization(String uuid, String name) throws InvalidObjectException{
final SessionFactory uuidResult = SessionFactoryRegistry.INSTANCE.getSessionFactory( uuid );
if ( uuidResult != null ) {
LOG.debugf( "Resolved SessionFactory by UUID [%s]", uuid );
return uuidResult;
}
// in case we were deserialized in a different JVM, look for an instance with the same name
// (provided we were given a name)
if ( name != null ) {
final SessionFactory namedResult = SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( name );
if ( namedResult != null ) {
LOG.debugf( "Resolved SessionFactory by name [%s]", name );
return namedResult;
}
}
throw new InvalidObjectException( "Could not find a SessionFactory [uuid=" + uuid + ",name=" + name + "]" );
}
protected DbManager()
throws DbException {
this.log = Logger.getLogger(this.getClass());
try {
// This step will read hibernate.cfg.xml
// and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
}
catch (HibernateException he) {
he.printStackTrace();
throw new DbException("Failed to initialize DbManager", he);
}
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
SessionFactory sf = getSessionFactory();
Assert.state(sf != null, "No SessionFactory set");
if (!TransactionSynchronizationManager.hasResource(sf)) {
// New Session to be bound for the current method's scope...
Session session = openSession(sf);
try {
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
return invocation.proceed();
}
finally {
SessionFactoryUtils.closeSession(session);
TransactionSynchronizationManager.unbindResource(sf);
}
}
else {
// Pre-bound Session found -> simply proceed.
return invocation.proceed();
}
}
@Test
public void selectTest(){
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user = session.get(User.class, 1);
System.out.println(user);
transaction.commit();
session.close();
sessionFactory.close();
}
public void init() {
if (incNestingCount() > 1) {
return;
}
SessionFactory sf = getSessionFactory();
if (sf == null) {
return;
}
if (TransactionSynchronizationManager.hasResource(sf)) {
// Do not modify the Session: just set the participate flag.
setParticipate(true);
}
else {
setParticipate(false);
LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor");
Session session = getSession();
HibernateRuntimeUtils.enableDynamicFilterEnablerIfPresent(sf, session);
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
}
}
public static void main(String[] args) {
// Prep Work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = (Employee) session.load(Employee.class, new Long(101));
System.out.println("Employee object loaded. " + emp);
tx.commit();
//merge example - data already present in tables
emp.setSalary(25000);
Transaction tx8 = session.beginTransaction();
Employee emp4 = (Employee) session.merge(emp);
System.out.println(emp4 == emp); // returns false
emp.setName("Test");
emp4.setName("Kumar");
System.out.println("15. Before committing merge transaction");
tx8.commit();
System.out.println("16. After committing merge transaction");
// Close resources
sessionFactory.close();
}
@Override
@Nullable
public SessionFactory getObject() {
EntityManagerFactory emf = getEntityManagerFactory();
Assert.state(emf != null, "EntityManagerFactory must not be null");
try {
Method getSessionFactory = emf.getClass().getMethod("getSessionFactory");
return (SessionFactory) ReflectionUtils.invokeMethod(getSessionFactory, emf);
}
catch (NoSuchMethodException ex) {
throw new IllegalStateException("No compatible Hibernate EntityManagerFactory found: " + ex);
}
}
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheRegionFactory() throws Exception {
final RegionFactory regionFactory = new NoCachingRegionFactory(null);
final List invocations = new ArrayList();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
@Override
public Configuration addInputStream(InputStream is) {
try {
is.close();
}
catch (IOException ex) {
}
invocations.add("addResource");
return this;
}
};
}
@Override
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(LocalRegionFactoryProxy.class.getName(),
config.getProperty(Environment.CACHE_REGION_FACTORY));
assertSame(regionFactory, LocalSessionFactoryBean.getConfigTimeRegionFactory());
invocations.add("newSessionFactory");
return null;
}
};
sfb.setCacheRegionFactory(regionFactory);
sfb.afterPropertiesSet();
assertTrue(sfb.getConfiguration() != null);
assertEquals("newSessionFactory", invocations.get(0));
}
@Override
public void sessionFactoryClosed(SessionFactory sessionFactory) {
SessionFactoryImplementor sfi = ( (SessionFactoryImplementor) sessionFactory );
sfi.getServiceRegistry().destroy();
ServiceRegistry basicRegistry = sfi.getServiceRegistry().getParentServiceRegistry();
( (ServiceRegistryImplementor) basicRegistry ).destroy();
}
private static void deleteGeometry(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("delete from TheData where id=:id");
query.setParameter("id",1L);
query.executeUpdate();
session.getTransaction().commit();
session.close();
}
public void stop() {
log.info("stopping service");
try {
InitialContext context = NamingHelper.getInitialContext( buildProperties() );
( (SessionFactory) context.lookup(boundName) ).close();
//context.unbind(boundName);
}
catch (Exception e) {
log.warn("exception while stopping service", e);
}
}
/**
* Open a Session for the given SessionFactory.
* <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 to use
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @since 5.0
* @see FlushMode#MANUAL
*/
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = openSession();
if (session == null) {
try {
session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
return session;
}
@Test
void set_metadata_from_dump(SessionFactory sessionFactory) {
ExampleHibernateDao dao = new ExampleHibernateDao(sessionFactory, new TestClock(), new TestActorProvider());
TestDump testRestoreDump = new TestDump.Builder()
.mode(DumpImportMode.RESTORE)
.createdBy("createdBy1")
.createdIp("createdIp1")
.createdAt(Instant.ofEpochSecond(23))
.updatedBy("updatedBy1")
.updatedIp("updatedIp1")
.updatedAt(Instant.ofEpochSecond(77))
.build();
ExampleModel model = new ExampleModel();
dao.setModelMetadataFromDump(model, testRestoreDump);
assertThat(model.createdBy).isEqualTo("createdBy1");
assertThat(model.createdIp).isEqualTo("createdIp1");
assertThat(model.createdAt).isEqualTo(Instant.ofEpochSecond(23));
assertThat(model.updatedBy).isEqualTo("updatedBy1");
assertThat(model.updatedIp).isEqualTo("updatedIp1");
assertThat(model.updatedAt).isEqualTo(Instant.ofEpochSecond(77));
dao.setModelMetadataFromDump(model, new TestDump.Builder()
.from(testRestoreDump)
.mode(DumpImportMode.CREATE)
.build());
assertThat(model.createdBy).isEqualTo("actorJid");
assertThat(model.createdIp).isEqualTo("actorIp");
assertThat(model.createdAt).isEqualTo(TestClock.NOW);
assertThat(model.updatedBy).isEqualTo("actorJid");
assertThat(model.updatedIp).isEqualTo("actorIp");
assertThat(model.updatedAt).isEqualTo(TestClock.NOW);
}
@TearDown
public void tearDownState() {
LOGGER.info("State - Teardown");
SessionFactory sessionFactory = session.getSessionFactory();
session.close();
sessionFactory.close();
LOGGER.info("State - Teardown complete");
}
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration()
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
@Before
public void setup() {
((ch.qos.logback.classic.Logger)LoggerFactory.getLogger("org.apache.cxf")).setLevel(Level.INFO);
jaxwsEnvironment = new JAXWSEnvironment("soap") {
/*
We create BasicAuthenticationInterceptor mock manually, because Mockito provided mock
does not get invoked by CXF
*/
@Override
protected BasicAuthenticationInterceptor createBasicAuthenticationInterceptor() {
return new BasicAuthenticationInterceptor() {
@Override
public void handleMessage(Message message) throws Fault {
mockBasicAuthInterceptorInvoked++;
}
};
}
};
when(mockInvokerBuilder.create(any(), any(Invoker.class))).thenReturn(mockInvoker);
jaxwsEnvironment.setInstrumentedInvokerBuilder(mockInvokerBuilder);
when(mockUnitOfWorkInvokerBuilder
.create(any(), any(Invoker.class), any(SessionFactory.class)))
.thenReturn(mockInvoker);
jaxwsEnvironment.setUnitOfWorkInvokerBuilder(mockUnitOfWorkInvokerBuilder);
mockBasicAuthInterceptorInvoked = 0;
testutils.setBus(jaxwsEnvironment.bus);
testutils.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
testutils.addNamespace("a", "http://jaxws.dropwizard.roskart.com/");
}
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(
sessionFactory);
return transactionManager;
}
@Bean
public HibernateTransactionManager transactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}
private IServiceStorage createServiceStorage(EnvironmentSettings envSettings, SessionFactory sessionFactory, IWorkspaceDispatcher workspaceDispatcher, IStaticServiceManager staticServiceManager, IDictionaryManager dictionaryManager,
IMessageStorage messageStorage) {
switch(envSettings.getStorageType()) {
case DB:
return new DatabaseServiceStorage(sessionFactory, staticServiceManager, dictionaryManager, messageStorage);
case FILE:
return new FileServiceStorage(envSettings.getFileStoragePath(), workspaceDispatcher, staticServiceManager, messageStorage);
case MEMORY:
return new MemoryServiceStorage();
default:
throw new EPSCommonException("Unsupported service storage type. Check your descriptor.xml file.");
}
}
/**
* Starts Hibernate.
*
* @param accessType Cache access type.
* @param igniteInstanceName Ignite instance name.
* @return Session factory.
*/
private SessionFactory startHibernate(org.hibernate.cache.spi.access.AccessType accessType, String igniteInstanceName) {
StandardServiceRegistryBuilder builder = registryBuilder();
for (Map.Entry<String, String> e : hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
builder.applySetting(e.getKey(), e.getValue());
// Use the same cache for Entity and Entity2.
builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, ENTITY_NAME);
StandardServiceRegistry srvcRegistry = builder.build();
MetadataSources metadataSources = new MetadataSources(srvcRegistry);
for (Class entityClass : getAnnotatedClasses())
metadataSources.addAnnotatedClass(entityClass);
Metadata metadata = metadataSources.buildMetadata();
for (PersistentClass entityBinding : metadata.getEntityBindings()) {
if (!entityBinding.isInherited())
((RootClass) entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
}
for (org.hibernate.mapping.Collection collectionBinding : metadata.getCollectionBindings())
collectionBinding.setCacheConcurrencyStrategy(accessType.getExternalName());
return metadata.buildSessionFactory();
}
@Override
protected SessionFactory newSessionFactory() {
Properties properties = getProperties();
return new Configuration()
.addProperties(properties)
.addAnnotatedClass(SecurityId.class)
.buildSessionFactory(
new StandardServiceRegistryBuilder()
.applySettings(properties)
.build()
);
}
/**
* Constructor.
*
* @param sessionFactory the session factory to communicate with the DB.
*/
@Autowired
public SqlReportEntitiesPersister(SessionFactory sessionFactory, Config config) {
this.sessionFactory =
Preconditions.checkNotNull(sessionFactory, "SessionFactory can not be null");
this.config = Preconditions.checkNotNull(config, "Config can not be null");
}
public SessionFactory findSessionFactory(String uuid, String name) {
SessionFactory sessionFactory = getSessionFactory( uuid );
if ( sessionFactory == null && StringHelper.isNotEmpty( name ) ) {
sessionFactory = getNamedSessionFactory( name );
}
return sessionFactory;
}
@Autowired
public PipelineStateDao(GoCache goCache,
TransactionTemplate transactionTemplate,
SqlSessionFactory sqlSessionFactory,
TransactionSynchronizationManager transactionSynchronizationManager,
SystemEnvironment systemEnvironment,
Database database,
SessionFactory sessionFactory) {
super(goCache, sqlSessionFactory, systemEnvironment, database);
this.transactionTemplate = transactionTemplate;
this.transactionSynchronizationManager = transactionSynchronizationManager;
this.sessionFactory = sessionFactory;
this.cacheKeyGenerator = new CacheKeyGenerator(getClass());
}
/**
* Unbinds the session (if one) current associated with the context for the
* given session.
*
* @param factory The factory for which to unbind the current session.
* @return The bound session if one, else null.
*/
public static Session unbind(SessionFactory factory) {
final Map<SessionFactory,Session> sessionMap = sessionMap();
Session existing = null;
if ( sessionMap != null ) {
existing = sessionMap.remove( factory );
doCleanup();
}
return existing;
}
/**
* Get a new Hibernate Session from the given SessionFactory.
* Will return a new Session even if there already is a pre-bound
* Session for the given SessionFactory.
* <p>Within a transaction, this method will create a new Session
* that shares the transaction's JDBC Connection. More specifically,
* it will use the same JDBC Connection as the pre-bound Hibernate Session.
* @param sessionFactory Hibernate SessionFactory to create the session with
* @param entityInterceptor Hibernate entity interceptor, or {@code null} if none
* @return the new Session
*/
@SuppressWarnings("deprecation")
public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) {
Assert.notNull(sessionFactory, "No SessionFactory specified");
try {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
if (sessionHolder != null && !sessionHolder.isEmpty()) {
if (entityInterceptor != null) {
return sessionFactory.openSession(sessionHolder.getAnySession().connection(), entityInterceptor);
}
else {
return sessionFactory.openSession(sessionHolder.getAnySession().connection());
}
}
else {
if (entityInterceptor != null) {
return sessionFactory.openSession(entityInterceptor);
}
else {
return sessionFactory.openSession();
}
}
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
public void testSessionStats() throws Exception {
SessionFactory sf = getSessions();
Statistics stats = sf.getStatistics();
boolean isStats = stats.isStatisticsEnabled();
stats.clear();
stats.setStatisticsEnabled(true);
Session s = sf.openSession();
assertEquals( 1, stats.getSessionOpenCount() );
s.close();
assertEquals( 1, stats.getSessionCloseCount() );
s = sf.openSession();
Transaction tx = s.beginTransaction();
A a = new A();
a.setName("mya");
s.save(a);
a.setName("b");
tx.commit();
s.close();
assertEquals( 1, stats.getFlushCount() );
s = sf.openSession();
tx = s.beginTransaction();
String hql = "from " + A.class.getName();
Query q = s.createQuery(hql);
q.list();
tx.commit();
s.close();
assertEquals(1, stats.getQueryExecutionCount() );
assertEquals(1, stats.getQueryStatistics(hql).getExecutionCount() );
stats.setStatisticsEnabled(isStats);
}