List of usage examples for org.hibernate Session getSessionFactory
SessionFactory getSessionFactory();
From source file:org.unitime.timetable.solver.jgroups.AbstractSolverServer.java
License:Apache License
@Override public void refreshInstructorSolution(Collection<Long> solverGroupIds) { org.hibernate.Session hibSession = new _RootDAO().createNewSession(); try {//from ww w . j a va 2 s . c o m SessionFactory hibSessionFactory = hibSession.getSessionFactory(); List<Long> classIds = (List<Long>) hibSession.createQuery( "select distinct c.uniqueId from Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false") .setParameterList("solverGroupId", solverGroupIds).list(); for (Long classId : classIds) { hibSessionFactory.getCache().evictEntity(Class_.class, classId); hibSessionFactory.getCache().evictCollection(Class_.class.getName() + ".classInstructors", classId); } List<Long> instructorIds = (List<Long>) hibSession.createQuery( "select i.uniqueId from DepartmentalInstructor i, SolverGroup g inner join g.departments d where " + "g.uniqueId in :solverGroupId and i.department = d") .setParameterList("solverGroupId", solverGroupIds).list(); for (Long instructorId : instructorIds) { hibSessionFactory.getCache().evictEntity(DepartmentalInstructor.class, instructorId); hibSessionFactory.getCache().evictCollection(DepartmentalInstructor.class.getName() + ".classes", instructorId); } List<Long> requestIds = (List<Long>) hibSession.createQuery( "select distinct r.uniqueId from Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false") .setParameterList("solverGroupId", solverGroupIds).list(); for (Long requestId : requestIds) { hibSessionFactory.getCache().evictEntity(TeachingRequest.class, requestId); hibSessionFactory.getCache() .evictCollection(TeachingRequest.class.getName() + ".assignedInstructors", requestId); } List<Long> offeringIds = (List<Long>) hibSession.createQuery( "select distinct c.schedulingSubpart.instrOfferingConfig.instructionalOffering.uniqueId from " + "Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false") .setParameterList("solverGroupId", solverGroupIds).list(); for (Long offeringId : offeringIds) { hibSessionFactory.getCache().evictEntity(InstructionalOffering.class, offeringId); hibSessionFactory.getCache().evictCollection( InstructionalOffering.class.getName() + ".offeringCoordinators", offeringId); } } finally { hibSession.close(); } }
From source file:org.vibur.dbcp.integration.ViburDBCPConnectionProviderTest.java
License:Apache License
@Test public void testSelectStatementWithStatementsCache() throws SQLException { Session session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession(); ConnectionProvider cp = ((SessionFactoryImplementor) session.getSessionFactory()).getServiceRegistry() .getService(ConnectionProvider.class); ViburDBCPDataSource ds = ((ViburDBCPConnectionProvider) cp).getDataSource(); ConcurrentMap<ConnMethod, StatementHolder> mockedStatementCache = mockStatementCache(ds); executeAndVerifySelectInSession(session); // resources/hibernate-with-stmt-cache.cfg.xml defines pool with 1 connection only, that's why // the second session will get and use the same underlying connection. session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession(); executeAndVerifySelectInSession(session); InOrder inOrder = inOrder(mockedStatementCache); inOrder.verify(mockedStatementCache).get(key1.capture()); inOrder.verify(mockedStatementCache).putIfAbsent(same(key1.getValue()), val1.capture()); inOrder.verify(mockedStatementCache).get(key2.capture()); assertEquals(1, mockedStatementCache.size()); assertTrue(mockedStatementCache.containsKey(key1.getValue())); assertEquals(key1.getValue(), key2.getValue()); assertEquals("prepareStatement", key1.getValue().getMethod().getName()); assertEquals(AVAILABLE, val1.getValue().state().get()); }
From source file:org.vulpe.model.dao.impl.jpa.AbstractVulpeBaseDAOJPA.java
License:Open Source License
public CallableStatement executeCallableStatement(final String name, final Integer returnType, final List<Parameter> parameters) throws VulpeApplicationException { CallableStatement cstmt = null; try {//from w w w .j a v a 2 s. com final Session session = (Session) entityManager.getDelegate(); final SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) session .getSessionFactory(); final ConnectionProvider connectionProvider = sessionFactoryImplementor.getConnectionProvider(); final Connection connection = connectionProvider.getConnection(); final StringBuilder call = new StringBuilder(); call.append(returnType == null ? "{call " : "{? = call "); call.append(name); int count = 0; if (parameters != null) { call.append("("); do { if (count > 0) { call.append(","); } call.append("?"); ++count; } while (count < parameters.size()); call.append(")"); } call.append("}"); if (parameters != null) { cstmt = connection.prepareCall(call.toString()); if (returnType != null) { if (returnType != 0) { cstmt.registerOutParameter(1, returnType); count = 1; } else { count = 0; } } for (Parameter parameter : parameters) { ++count; if (parameter.getType() == Types.ARRAY) { // Connection nativeConnection = // cstmt.getConnection().getMetaData().getConnection(); // ArrayDescriptor objectArrayDescriptor = // ArrayDescriptor.createDescriptor( // parameter.getArrayType(), nativeConnection); // Array array = new ARRAY(objectArrayDescriptor, // nativeConnection, parameter // .getArrayValues()); // cstmt.setArray(count, array); LOG.info(""); } else { cstmt.setObject(count, parameter.getValue(), parameter.getType()); } if (parameter.isOut()) { if (parameter.getType() == Types.ARRAY) { cstmt.registerOutParameter(count, Types.ARRAY, parameter.getArrayType()); } else { cstmt.registerOutParameter(count, parameter.getType()); } } } } cstmt.execute(); } catch (SQLException e) { throw new VulpeApplicationException(e.getMessage()); } return cstmt; }
From source file:org.wildfly.extras.db_bootstrap.DbBootstrapScanDetectorProcessor.java
License:Apache License
/** * Wrap transaction around the invoke with the {@link Session}, if any exception throw it roll back the tx otherwise commit * the tx;/*from ww w .j av a2 s.c o m*/ * * @param bootstrapDatabaseAnnotation - the boostrap configuration source * @param classLoader - The classloader to load the hibernate resources from * @param method - the method to invoke * @param bootstrapClass - the class to invoke the method on * @throws Exception */ private void invokeWithSession(final BootstrapDatabase bootstrapDatabaseAnnotation, final ClassLoader classLoader, Method method, Object bootstrapClass) throws Exception { Session session = createSession(bootstrapDatabaseAnnotation, classLoader); Transaction tx = session.beginTransaction(); try { method.invoke(bootstrapClass, session); } catch (Exception e) { DbBootstrapLogger.ROOT_LOGGER.error(String.format("Unable to invoke method %s ", method.getName()), e); tx.rollback(); } finally { if (tx.isActive()) { tx.commit(); } session.close(); session.getSessionFactory().close(); } }
From source file:org.xchain.namespaces.hibernate.GetCommand.java
License:Apache License
/** * Performs a Get for the given class-name with the given id and stores the result in the given * result QName.//from w ww . j a v a 2 s.c o m */ public boolean execute(JXPathContext context) throws Exception { if (!hasId()) throw new Exception("A get command must have an id."); if (!hasClassName()) throw new Exception("A get command must have a class-name."); // Get the session from the context. Session session = HibernateLifecycle.getCurrentSession(getName(context)); // Get the metadata of the entity to be loaded from hibernate ClassMetadata metadata = session.getSessionFactory().getClassMetadata(getClassName(context)); storeValue(context, session.get(getClassName(context), getId(context, metadata.getIdentifierType().getReturnedClass()))); // The get is executed. return false; }
From source file:org.zanata.model.validator.UniqueValidator.java
License:Open Source License
private int countRows(Object value) { // we need to use entityManager.unwrap because injected session will // be a weld proxy and criteria.getExecutableCriteria method will try // to cast it to SessionImplementor (ClassCastException) Session session = entityManager.unwrap(Session.class); ClassMetadata metadata = session.getSessionFactory().getClassMetadata(value.getClass()); String idName = metadata.getIdentifierPropertyName(); // FIXME was EntityMode.POJO Serializable id = metadata.getIdentifier(value, null); DetachedCriteria criteria = DetachedCriteria.forClass(value.getClass()); for (String property : parameters.properties()) { // FIXME was EntityMode.POJO criteria.add(Restrictions.eq(property, metadata.getPropertyValue(value, property))); }/*from w w w . ja va2 s . co m*/ // Id property if (id != null) { criteria.add(Restrictions.ne(idName, id)); } criteria.setProjection(Projections.rowCount()); // change the flush mode temporarily to perform the query or else // incomplete entities will try to get flushed // After the query, go back to the original mode FlushMode flushMode = session.getFlushMode(); session.setFlushMode(FlushMode.MANUAL); List results = criteria.getExecutableCriteria(session).list(); Number count = (Number) results.iterator().next(); session.setFlushMode(flushMode); return count.intValue(); }
From source file:osgi.jee.samples.jpa.aries.hibernate.derby.internal.services.AriesHibernateDerbyPersistenceService.java
License:Open Source License
/** * {@inheritDoc}//w ww. jav a 2 s .c om * @see osgi.jee.samples.jpa.api.services.persistence.PersistenceService#extractConnection(javax.persistence.EntityManager) */ public Connection extractConnection(EntityManager entityManager) { Session session = entityManager.unwrap(Session.class); SessionFactory sessionFactory = session.getSessionFactory(); if (sessionFactory instanceof SessionFactoryImplementor) { @SuppressWarnings("deprecation") ConnectionProvider connectionProvider = ((SessionFactoryImplementor) sessionFactory) .getConnectionProvider(); try { return connectionProvider.getConnection(); } catch (SQLException e) { return null; } } return null; }
From source file:persistence.PersonDAO.java
public List<Person> getByName(final String name) { Session session = Conection.getSessionFactory().openSession(); List<Person> listPerson = session.createQuery("select p from Person as p where p.name = :paramName") .setParameter("paramName", name).list(); session.getSessionFactory().close(); return listPerson; }
From source file:sernet.gs.ui.rcp.main.service.migrationcommands.MigrateDbTo1_01D.java
License:Open Source License
/** * reads in hibernatesession configured database dialog * @return//from w w w . ja v a 2 s . co m */ @SuppressWarnings({ "unchecked", "restriction" }) private String getHibernateDialect() { return (String) getDaoFactory().getDAO(Attachment.class).executeCallback(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { return ((SessionFactoryImplementor) session.getSessionFactory()).getDialect().toString(); } }); }
From source file:storybook.model.dao.SbGenericDAOImpl.java
License:Open Source License
public SbGenericDAOImpl(Session session) { this.session = session; setSessionFactory(session.getSessionFactory()); }