Java源码示例:org.hibernate.context.internal.ManagedSessionContext
示例1
/**
* Clears all given tables which are mentioned using the given sessionFactory
*/
private void clearDb(Class[] tables, SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
ManagedSessionContext.bind(session);
Transaction tx = session.beginTransaction();
try {
session.createSQLQuery("set foreign_key_checks=0").executeUpdate();
for (Class anEntity : tables) {
session.createSQLQuery("delete from " + anEntity.getSimpleName() + "s").executeUpdate(); //table name is plural form of class name, so appending 's'
}
session.createSQLQuery("set foreign_key_checks=1").executeUpdate();
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
throw new RuntimeException("Unable to clear tables. Exception: " + e.getMessage(), e);
} finally {
if (session != null) {
ManagedSessionContext.unbind(sessionFactory);
session.close();
}
}
}
示例2
@Before
public void setUp() throws Exception {
Session session = sessionFactory.getSchedulerSessionFactory().openSession();
ManagedSessionContext.bind(session);
Transaction tx = session.beginTransaction();
try {
session.createSQLQuery("delete from ScheduledEvents").executeUpdate();
tx.commit();
} finally {
if (session != null) {
ManagedSessionContext.unbind(session.getSessionFactory());
session.close();
sessionFactory.clear();
}
}
}
示例3
@Before
public void setUp() throws Exception {
context.setThreadLocalSession(context.getSchedulerSessionFactory().openSession());
Session session = context.getThreadLocalSession();
ManagedSessionContext.bind(session);
Transaction tx = session.beginTransaction();
try {
session.createSQLQuery("delete from ScheduledMessages").executeUpdate();
tx.commit();
} finally {
if(session != null) {
ManagedSessionContext.unbind(context.getThreadLocalSession().getSessionFactory());
session.close();
context.clear();
}
}
}
示例4
@Override
public String onConnect(Session session) {
for (HttpCookie cookie : session.getUpgradeRequest().getCookies()) {
if ("auth-token".equals(cookie.getName())) {
String authToken = cookie.getValue();
TokenAuthenticator authenticator = getAuthenticator();
org.hibernate.Session hSession = sessionFactory.openSession();
ManagedSessionContext.bind(hSession);
Optional<BasicToken> token;
try {
token = authenticator.authenticate(authToken);
} catch (AuthenticationException e) {
e.printStackTrace();
return null;
}
if (!token.isPresent()) {
return null;
}
hSession.close();
return token.get().getUserId();
}
}
return null;
}
示例5
@Test
public void get() {
SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
ManagedSessionContext.bind(sessionFactory.openSession());
SystemParameterDao dao = new SystemParameterDao(sessionFactory);
SystemParameter parameter = new SystemParameter();
parameter.setValue("ROBE");
parameter.setKey("TEST");
parameter = dao.create(parameter);
dao.flush();
Object value = SystemParameterCache.get("DEFAULT", "default"); // TODO GuiceBundle not initialized
Assert.assertTrue(value.equals("default"));
Object value2 = SystemParameterCache.get("TEST", "none");
Assert.assertTrue(value2.equals("ROBE"));
dao.detach(parameter);
dao.delete(parameter);
dao.flush();
}
示例6
public static <T> T call(SessionFactory sessionFactory, SessionRunnerReturningValue<T> sessionRunner) {
final Session session = sessionFactory.openSession();
if (ManagedSessionContext.hasBind(sessionFactory)) {
throw new IllegalStateException("Already in a unit of work!");
}
T t = null;
try {
ManagedSessionContext.bind(session);
session.beginTransaction();
try {
t = sessionRunner.runInSession();
commitTransaction(session);
} catch (Exception e) {
rollbackTransaction(session);
UnitOfWork.<RuntimeException> rethrow(e);
}
} finally {
session.close();
ManagedSessionContext.unbind(sessionFactory);
}
return t;
}
示例7
@Override
public void afterEach(ExtensionContext context) {
SessionContext sessionContext = getStore(context).get(context.getUniqueId(), SessionContext.class);
if (sessionContext != null) {
sessionContext.getSession().close();
ManagedSessionContext.unbind(sessionContext.getSessionFactory());
sessionContext.getSessionFactory().close();
}
}
示例8
private void openSession(SessionFactory sessionFactory, ExtensionContext context) {
Session session = sessionFactory.openSession();
Transaction txn = session.beginTransaction();
ManagedSessionContext.bind(session);
SessionContext sessionContext = new SessionContext(sessionFactory, session, txn);
getStore(context).put(context.getUniqueId(), sessionContext);
}
示例9
private CurrentSessionContext buildCurrentSessionContext() {
String impl = (String) properties.get( Environment.CURRENT_SESSION_CONTEXT_CLASS );
// for backward-compatibility
if ( impl == null ) {
if ( canAccessTransactionManager() ) {
impl = "jta";
}
else {
return null;
}
}
if ( "jta".equals( impl ) ) {
// if ( ! transactionFactory().compatibleWithJtaSynchronization() ) {
// LOG.autoFlushWillNotWork();
// }
return new JTASessionContext( this );
}
else if ( "thread".equals( impl ) ) {
return new ThreadLocalSessionContext( this );
}
else if ( "managed".equals( impl ) ) {
return new ManagedSessionContext( this );
}
else {
try {
Class implClass = serviceRegistry.getService( ClassLoaderService.class ).classForName( impl );
return (CurrentSessionContext)
implClass.getConstructor( new Class[] { SessionFactoryImplementor.class } )
.newInstance( this );
}
catch( Throwable t ) {
LOG.unableToConstructCurrentSessionContext( impl, t );
return null;
}
}
}
示例10
/**
* Creates a new session context and sets the related session factory.
*
* @param theSessionFactory
* Context session factory. Cannot be null.
*/
public TransactionAwareSessionContext(final SessionFactoryImplementor theSessionFactory) {
Validate.notNull(theSessionFactory, "The session factory cannot be null.");
defaultSessionContext = new SpringSessionContext(theSessionFactory);
localSessionContext = new ManagedSessionContext(theSessionFactory);
sessionFactory = theSessionFactory;
}
示例11
/**
* Binds the configured session to Spring's transaction manager strategy if there's no session.
*
* @return Returns the configured session, or the one managed by Spring. Never returns null.
*/
@Override
public Session currentSession() {
try {
Session s = defaultSessionContext.currentSession();
return s;
} catch (HibernateException cause) {
// There's no session bound to the current thread. Let's open one if
// needed.
if (ManagedSessionContext.hasBind(sessionFactory)) {
return localSessionContext.currentSession();
}
Session session;
session = sessionFactory.openSession();
TransactionAwareSessionContext.logger.warn("No Session bound to current Thread. Opened new Session ["
+ session + "]. Transaction: " + session.getTransaction());
if (registerSynchronization(session)) {
// Normalizes Session flush mode, defaulting it to AUTO. Required for
// synchronization. LDEV-4696 Updated for Hibernate 5.3. See SPR-14364.
FlushMode flushMode = session.getHibernateFlushMode();
if (FlushMode.MANUAL.equals(flushMode)
&& !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.AUTO);
}
}
ManagedSessionContext.bind(session);
return session;
}
}
示例12
/**
* Creates a transaction synchronization object for the specified session.
*
* @param session
* Session to synchronize using the created object. Cannot be null.
* @return A valid transaction synchronization. Never returns null.
*/
private TransactionSynchronization createTransactionSynchronization(final Session session) {
return new TransactionSynchronizationAdapter() {
@Override
public void afterCompletion(final int status) {
session.close();
ManagedSessionContext.unbind(sessionFactory);
}
};
}
示例13
private void clean() throws Exception {
Session session = sessionFactory.getSchedulerSessionFactory().openSession();
ManagedSessionContext.bind(session);
Transaction tx = session.beginTransaction();
try {
session.createSQLQuery("delete from ClientElb").executeUpdate();
tx.commit();
} finally {
if (session != null) {
ManagedSessionContext.unbind(session.getSessionFactory());
session.close();
sessionFactory.clear();
}
}
}
示例14
private void clean() throws Exception {
Session session = sessionFactory.getSchedulerSessionFactory().openSession();
ManagedSessionContext.bind(session);
Transaction tx = session.beginTransaction();
try {
session.createSQLQuery("delete from ClientElb").executeUpdate();
tx.commit();
} finally {
if (session != null) {
ManagedSessionContext.unbind(session.getSessionFactory());
session.close();
sessionFactory.clear();
}
}
}
示例15
public JobPersister(ConcurrentHashMap<String, JobInfo> jobs) {
SessionFactory sessionFactory = GuiceBundle.getInjector().getInstance(SessionFactory.class);
ManagedSessionContext.bind(sessionFactory.openSession());
JobDao jobDao = new JobDao(sessionFactory);
TriggerDao triggerDao = new TriggerDao(sessionFactory);
for (JobInfo info : jobs.values()) {
insertOrUpdate(jobDao, info, triggerDao);
}
sessionFactory.getCurrentSession().flush();
sessionFactory.getCurrentSession().close();
ManagedSessionContext.unbind(sessionFactory);
}
示例16
public static void fillCache() {
SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
ManagedSessionContext.bind(sessionFactory.openSession());
SystemParameterDao dao = new SystemParameterDao(sessionFactory);
List<SystemParameter> parameters = dao.findAllStrict();
for (SystemParameter parameter : parameters) {
cache.put(parameter.getKey(), parameter.getValue());
dao.detach(parameter);// TODO
}
}
示例17
@Test
public void getRolePermissions() throws IOException {
SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
ManagedSessionContext.bind(sessionFactory.openSession());
RoleDao roleDao = new RoleDao(sessionFactory);
Role role = roleDao.findByCode("all");
Assert.assertTrue(role != null);
TestRequest request = getRequestBuilder().endpoint(role.getId() + "/permissions").build();
TestResponse response = client.get(request);
Map result = response.get(Map.class);
Assert.assertTrue(result.get("menu") != null);
Assert.assertTrue(result.get("service") != null);
ManagedSessionContext.unbind(sessionFactory);
}
示例18
@Before
public void before() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (sessionFactory == null) {
sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
ManagedSessionContext.bind(sessionFactory.openSession());
this.daoClazz = (Class<D>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
dao = daoClazz.getDeclaredConstructor(SessionFactory.class).newInstance(sessionFactory);
}
}
示例19
/**
* If present, backup current the session in {@link ManagedSessionContext} and unbinds it.
*/
private void storePreviousSession() {
if (ManagedSessionContext.hasBind(SESSION_FACTORY)) {
SESSIONS.get().add(SESSION_FACTORY.getCurrentSession());
ManagedSessionContext.unbind(SESSION_FACTORY);
}
}
示例20
/**
* Closes and unbinds the current session. <br/>
* If {@link ManagedSessionContext} had a session before the current session, re-binds it to {@link ManagedSessionContext}
*/
private void finish() {
try {
if (session != null) {
session.close();
}
} finally {
ManagedSessionContext.unbind(SESSION_FACTORY);
if (!SESSIONS.get().isEmpty()) {
ManagedSessionContext.bind(SESSIONS.get().pop());
}
}
}
示例21
@Override
public Object invoke(Exchange exchange, Object o) {
Object result;
String methodname = this.getTargetMethod(exchange).getName();
if (unitOfWorkMethods.containsKey(methodname)) {
final Session session = sessionFactory.openSession();
UnitOfWork unitOfWork = unitOfWorkMethods.get(methodname);
try {
configureSession(session, unitOfWork);
ManagedSessionContext.bind(session);
beginTransaction(session, unitOfWork);
try {
result = underlying.invoke(exchange, o);
commitTransaction(session, unitOfWork);
return result;
} catch (Exception e) {
rollbackTransaction(session, unitOfWork);
this.<RuntimeException>rethrow(e); // unchecked rethrow
return null; // avoid compiler warning
}
} finally {
session.close();
ManagedSessionContext.unbind(sessionFactory);
}
}
else {
return underlying.invoke(exchange, o);
}
}
示例22
/**
* Opens a new session, sets flush mode and bind this session to {@link ManagedSessionContext}
*/
private void configureNewSession() {
session = SESSION_FACTORY.openSession();
session.setFlushMode(flushMode);
ManagedSessionContext.bind(session);
}