Java Code Examples for org.hibernate.Session

The following are top voted examples for showing how to use org.hibernate.Session. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ImageClassify   File: CompositionService.java   View source code 6 votes vote down vote up
@Override
public List<Integer> getComposition(int task_id) {
	 
	List<Integer> img_ids = new ArrayList<Integer>();
       Session session = HibernateUtils.getSession();//生成Session实例
	Transaction tx = session.beginTransaction();//生成事务实例  
	 try {
		 img_ids = session.createQuery("SELECT img_id FROM Composition WHERE task_id = ?").setInteger(0, task_id).list();
		 tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	}
	 return img_ids;
}
 
Example 2
Project: ImageClassify   File: InterestService.java   View source code 6 votes vote down vote up
@Override
public int deleteInterests(int user_id) {  
			Session session = HibernateUtils.getSession(); //生成session实例
		    Transaction tx = session.beginTransaction();  //创建transaction实例 
		    int temp = 0;
		    try {  
		    	String hql = "delete from Interest where user_id  =  ?"; 
		    	Query query = session.createQuery(hql);
		    	query.setInteger(0, user_id);  
		    	temp = query.executeUpdate(); 
		    	tx.commit();            //提交事务  
			} catch (Exception e) {
				e.printStackTrace();
				tx.rollback();   
			}finally {
			  HibernateUtils.closeSession();  //关闭Session实例
			} 
		    return temp;
}
 
Example 3
Project: unitimes   File: WSCHByDepartmentDayOfWeekHourOfDay.java   View source code 6 votes vote down vote up
@Override
public void createRoomUtilizationReportFor(PointInTimeData pointInTimeData, Session hibSession) {
	
	calculatePeriodsWithEnrollments(pointInTimeData, hibSession);
	
	int minute = (startOnHalfHour ? 30 : 0);
	for(Department department : depts) {
		for(int dayOfWeek = 1 ; dayOfWeek < 8 ; dayOfWeek++) {
			ArrayList<String> row = new ArrayList<String>();
			row.add(department.getDeptCode());
			row.add(department.getAbbreviation());
			row.add(department.getName());
			row.add(getDayOfWeekLabel(periodDayOfWeek(dayOfWeek)));
			for(int hourOfDay = 0 ; hourOfDay < 24 ; hourOfDay++) {
				String key = getPeriodTag(department.getUniqueId().toString(), dayOfWeek, hourOfDay, minute);
				row.add(periodEnrollmentMap.get(key) == null ? "0": "" + periodEnrollmentMap.get(key).getWeeklyStudentEnrollment());
			}
			addDataRow(row);			
		}
	}
			
}
 
Example 4
Project: Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update   File: TestClass.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	Configuration cfg=null;
	SessionFactory factory=null;
	Session ses=null;
	Transaction tx=null;
			cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
			factory=cfg.buildSessionFactory();
		ses=factory.openSession();
	
		 String hql="select item_name from bigbazarModel where bazarid=:id";
		 Query q=ses.createQuery(hql);
		 		q.setParameter("id", 1001);
		 			String s=(String) q.uniqueResult();
		 			System.out.println("\t\t"+s);
		 			
		 			factory.close();

}
 
Example 5
Project: unitimes   File: WSEByDayOfWeekAndPeriod.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private HashSet<PitClass> findAllPitClassesWithContactHoursForDepartmentsAndSubjectAreas(
		PointInTimeData pointInTimeData, Session hibSession) {
	
	HashSet<PitClass> pitClasses = new HashSet<PitClass>();
			
	for(Long deptId : getDepartmentIds()) {
		List<PitClass> pitClassesQueryResult = findAllPitClassesWithContactHoursForDepartment(pointInTimeData, deptId, hibSession);
		for(PitClass pc : pitClassesQueryResult) {
			if(pc.getPitSchedulingSubpart().getPitInstrOfferingConfig().getPitInstructionalOffering().getControllingPitCourseOffering().isIsControl().booleanValue() 
					&& getSubjectAreaIds().contains(pc.getPitSchedulingSubpart().getPitInstrOfferingConfig().getPitInstructionalOffering().getControllingPitCourseOffering().getSubjectArea().getUniqueId())) {
				pitClasses.add(pc);
			};
		}
	}
	return(pitClasses);

}
 
Example 6
Project: Equella   File: GenericInstitionalDaoImpl.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
@Transactional
public List<ID> enumerateAllIds()
{
	return getHibernateTemplate().executeFind(new TLEHibernateCallback()
	{
		@Override
		public Object doInHibernate(Session session) throws HibernateException
		{
			// NOTE: Don't order by name here - use NumberStringComparator
			// on the returned list.
			Query query = session.createQuery("select id from " + getPersistentClass().getName() //$NON-NLS-1$
				+ " where institution = :institution"); //$NON-NLS-1$
			query.setParameter("institution", CurrentInstitution.get()); //$NON-NLS-1$
			query.setCacheable(true);
			query.setReadOnly(true);
			return query.list();
		}
	});
}
 
Example 7
Project: ImageClassify   File: CheckInService.java   View source code 6 votes vote down vote up
@Override
public List<CheckIn> getCheckIns(int user_id) {
	
	 List<CheckIn> checkIns=new ArrayList<CheckIn>();
        Session session=HibernateUtils.getSession();//生成Session实例
	 Transaction tx=session.beginTransaction();//生成事务实例 
	 
	 try {
		 //select * from checkin where user_id=user_id order by checkin_time asc
		 checkIns= session.createCriteria(CheckIn.class).add(Restrictions.eq("user_id", user_id)).addOrder(Order.asc("checkin_time")).list();				 
		 tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	}
	 return checkIns; 
}
 
Example 8
Project: dhus-core   File: FileScannerDao.java   View source code 6 votes vote down vote up
@Override
public void delete (final FileScanner scanner)
{
   getHibernateTemplate ().execute (new HibernateCallback<Void>()
   {
      @Override
      public Void doInHibernate (Session session) throws HibernateException,
         SQLException
      {
         String sql = "DELETE FROM FILE_SCANNER_PREFERENCES " +
            "WHERE FILE_SCANNER_ID = ?";
         SQLQuery query = session.createSQLQuery (sql);
         query.setLong (0, scanner.getId ());
         query.executeUpdate ();
         return null;
      }
   });
   super.delete (scanner);
}
 
Example 9
Project: sjk   File: AppDaoImpl.java   View source code 6 votes vote down vote up
@Override
public List<App> findData() {
    Session session = null;
    List<App> list = null;
    try {
        session = this.sessionFactory.openSession();
        Query q = session.createQuery("from App app where app.hidden = false");
        list = HibernateHelper.list(q);
        // if (list != null) {
        // logger.debug("in findData all .{} ", list.size());
        // }
    } catch (Exception e) {
        logger.error("error:", e);
    } finally {
        session.close();
    }
    return list;
}
 
Example 10
Project: lams   File: OpenSessionInterceptor.java   View source code 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession();
		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();
	}
}
 
Example 11
Project: OSWf-OSWorkflow-fork   File: HibernateStore.java   View source code 6 votes vote down vote up
public void moveToHistory(Step step, int actionId, Date finishDate, String status, String actor) throws WorkflowStoreException {

        Session session = null;
        
        try {
            
            session = sessionFactory.openSession();
            session.refresh(step);

            super.markFinished(step, actionId, finishDate, status, actor);
            update(session, step);

            HibernateStep currentStep = (HibernateStep)step;
            HibernateStep historyStep = new HibernateHistoryStep(currentStep);
            HibernateProcessInstance entry = currentStep.getEntry();

            entry.removeCurrentStep(currentStep);
            entry.addHistoryStep(historyStep);

            // Session transaction managed by the delete, save and update DAO methods
            delete(session, currentStep);
            save(session, historyStep);
            update(session, entry);
       
            if(logger.isDebugEnabled()) {
                logger.debug(historyStep.toString());
                logger.debug(entry.toString());
            }
       
        } catch(HibernateException hibernateException) {
            throw new WorkflowStoreException(hibernateException);
        } finally {

            if (session != null)
                session.close();
        }
        
        // Logging the results of this action

    }
 
Example 12
Project: ImageClassify   File: MarkService.java   View source code 6 votes vote down vote up
@Override
public List<String> getMarkListByUserId(int user_id) {
	List<String> accuracy = new ArrayList<String>();
       Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例 
	 
	 try {
		 accuracy = session.createQuery("select mark_accuracy from Mark where user_id = ?").setInteger(0, user_id).list();
		 tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	}
	 return accuracy;
}
 
Example 13
Project: ImageClassify   File: AdminService.java   View source code 6 votes vote down vote up
@Override
public int updateUserByAdmin(User user){
	Session session = HibernateUtils.getSession();
	 Transaction tx = session.beginTransaction();
	 int aa = 0;
	 try {
		Query query = session.createQuery("update User u set u.username =?,u.sex = ?,u.integral=?,u.accuracy=? where u.user_id = ?");  
	    query.setString(0, user.getUsername());
	    query.setString(1, user.getSex());
	    query.setInteger(2, user.getIntegral());
	    query.setString(3, user.getAccuracy());
	    query.setInteger(4, user.getUser_id());
		aa = query.executeUpdate();  
		tx.commit(); 
	} catch (Exception e) {
		 e.printStackTrace();
		 tx.rollback(); 
	}finally {
		HibernateUtils.closeSession();
	}  
	return aa;
}
 
Example 14
Project: ImageClassify   File: ImageService.java   View source code 6 votes vote down vote up
@Override
public int getAmountByCategoryId(int category_id) {
	 String sql = "SELECT COUNT(*) FROM image,image_category,category WHERE image.img_id = image_category.img_id AND category.category_id = image_category.category_id AND image.img_is_finish <>0 AND category.category_id = "+category_id;
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例  
	  int amount = 0;
	 try { 
	 List arr  =  session.createSQLQuery(sql).list(); 
	 amount = Integer.parseInt(arr.get(0).toString());
	 tx.commit();//提交事务 
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	} 
	return amount;
}
 
Example 15
Project: uflo   File: DeleteProcessDefinitionCommand.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Object execute(Context context) {
	ProcessService processService=context.getProcessService();
	ProcessInstanceQuery query=context.getProcessService().createProcessInstanceQuery();
	query.processId(processDefinition.getId());
	Session session=context.getSession();
	for(ProcessInstance pi:query.list()){
		processService.deleteProcessInstance(pi);
		session.createQuery("delete "+Variable.class.getName()+" where processInstanceId=:processInstanceId").setLong("processInstanceId", pi.getId()).executeUpdate();
	}
	
	List<HistoryProcessInstance> hisInstances=session.createQuery("from "+HistoryProcessInstance.class.getName()+" where processId=:processId").setLong("processId", processDefinition.getId()).list();
	for(HistoryProcessInstance instance:hisInstances){
		session.createQuery("delete "+HistoryVariable.class.getName()+" where historyProcessInstanceId=:historyProcessInstanceId").setLong("historyProcessInstanceId", instance.getId()).executeUpdate();
	}
	
	session.createQuery("delete "+Blob.class.getName()+" where processId=:processId").setLong("processId", processDefinition.getId()).executeUpdate();
	session.createQuery("delete "+HistoryProcessInstance.class.getName()+" where processId=:processId").setLong("processId", processDefinition.getId()).executeUpdate();
	session.createQuery("delete "+HistoryTask.class.getName()+" where processId=:processId").setLong("processId", processDefinition.getId()).executeUpdate();
	session.createQuery("delete "+HistoryActivity.class.getName()+" where processId=:processId").setLong("processId", processDefinition.getId()).executeUpdate();
	session.delete(processDefinition);
	return null;
}
 
Example 16
Project: DWSurvey   File: SurveyAnswerDaoImpl.java   View source code 6 votes vote down vote up
private int saveQuOrderMaps(SurveyAnswer surveyAnswer,
		Map<String, Object> quOrderMaps, Session session) {
	String surveyId=surveyAnswer.getSurveyId();
	String surveyAnswerId=surveyAnswer.getId();
	
	int answerQuCount=0;
	if(quOrderMaps!=null){
		for (String key : quOrderMaps.keySet()) {
			String quId=key;
			Map<String,Object> mapRows=(Map<String, Object>) quOrderMaps.get(key);
			for (String keyRow : mapRows.keySet()) {
				answerQuCount++;
				String rowId=keyRow;
				String orderNumValue=mapRows.get(keyRow).toString();
				AnOrder anScore=new AnOrder(surveyId,surveyAnswerId,quId,rowId,orderNumValue);
				session.save(anScore);
			}
		}
	}
	return answerQuCount;
}
 
Example 17
Project: FlashBoard   File: QuizDaoImpl.java   View source code 6 votes vote down vote up
@Override
public Quiz getQuizById(int quizId) {
	Session session = HibernateUtil.getSession();
	Criteria criteria;
	Quiz test = null;
	
	try {
		criteria = session.createCriteria(Quiz.class);
		//Adds like restriction to search for a particular username
		test = (Quiz)criteria.add(Restrictions.like("quizId", quizId)).uniqueResult();
	}
	catch(HibernateException he) {
		he.printStackTrace();
	}finally {
		session.close();
	}
	return test;
}
 
Example 18
Project: bdf2   File: ValidatorMaintain.java   View source code 6 votes vote down vote up
@DataResolver
public void saveValidators(Collection<ValidatorDef> validators){
	Session session=this.getSessionFactory().openSession();
	try{
		for(ValidatorDef v:validators){
			EntityState state=EntityUtils.getState(v);
			if(state.equals(EntityState.NEW)){
				v.setId(UUID.randomUUID().toString());
				session.save(v);
			}
			if(state.equals(EntityState.DELETED)){
				session.delete(v);
			}
			if(state.equals(EntityState.MODIFIED)){
				session.update(v);
			}
		}			
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 19
Project: unitimes   File: StandardEventNotes.java   View source code 6 votes vote down vote up
@Override
@PreAuthorize("checkPermission('StandardEventNotes')")
public void update(Record record, SessionContext context, Session hibSession) {
	StandardEventNote note = StandardEventNoteDAO.getInstance().get(record.getUniqueId());
	if (note == null) return;
	if (note instanceof StandardEventNoteGlobal) {
		context.checkPermission(Right.StandardEventNotesGlobalEdit);
		update(note, record, context, hibSession);
	} else if (note instanceof StandardEventNoteSession) {
		context.checkPermission(((StandardEventNoteSession)note).getSession(), Right.StandardEventNotesSessionEdit);
		update(note, record, context, hibSession);
	} else if (note instanceof StandardEventNoteDepartment) {
		context.checkPermission(((StandardEventNoteDepartment)note).getDepartment(), Right.StandardEventNotesDepartmentEdit);
		update(note, record, context, hibSession);
	}
}
 
Example 20
Project: sjk   File: AppDaoImpl.java   View source code 6 votes vote down vote up
@Override
public Integer save(App entity) {
    Session session = null;
    Integer pkId = null;
    try {
        session = sessionFactory.openSession();
        pkId = (Integer) session.save(entity);
    } catch (Exception e) {
        logger.error("error:", e);
    } finally {
        session.flush();
        session.clear();
        session.close();
    }

    return pkId;
}
 
Example 21
Project: dhus-core   File: FileScannerDao.java   View source code 6 votes vote down vote up
public int deleteCollectionReferences(final Collection collection)
{
   return getHibernateTemplate().execute  (
      new HibernateCallback<Integer>()
      {
         public Integer doInHibernate(Session session) 
            throws HibernateException, SQLException
         {
            String sql = "DELETE FROM FILESCANNER_COLLECTIONS s " +
                     " WHERE s.COLLECTIONS_UUID = :cid";
            SQLQuery query = session.createSQLQuery(sql);
            query.setString ("cid", collection.getUUID());
            return query.executeUpdate ();
         }
      });
}
 
Example 22
Project: dhus-core   File: DaoUtils.java   View source code 6 votes vote down vote up
public static void optimize ()
{
   HibernateDaoLocalSupport support = ApplicationContextProvider.getBean (
         HibernateDaoLocalSupport.class);
   support.getHibernateTemplate ().flush ();
   support.getHibernateTemplate ().executeWithNativeSession (
      new HibernateCallback<Void> ()
      {
         @Override
         public Void doInHibernate (Session session) throws
               HibernateException, SQLException
         {
            SQLQuery query = session.createSQLQuery ("CHECKPOINT DEFRAG");
            query.executeUpdate ();
            return null;
         }
      });
}
 
Example 23
Project: unitimes   File: InstructionalMethods.java   View source code 6 votes vote down vote up
protected void update(InstructionalMethod type, Record record, SessionContext context, Session hibSession) {
	if (type == null) return;
	if (ToolBox.equals(type.getReference(), record.getField(0)) &&
		ToolBox.equals(type.getLabel(), record.getField(2)) &&
		type.getVisible() == "true".equals(record.getField(2))) return;
	type.setReference(record.getField(0));
	type.setLabel(record.getField(1));
	type.setVisible("true".equals(record.getField(2)));
	hibSession.saveOrUpdate(type);
	ChangeLog.addChange(hibSession,
			context,
			type,
			type.getReference(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			null);
}
 
Example 24
Project: sjk   File: AppDaoTest.java   View source code 6 votes vote down vote up
@Test
public void testupdateIncrementDownload() {
    short catalog = 1;
    Integer subCatalog = 3;
    String sort = null;
    String order = null;
    int currentPage = 1;
    int pageSize = 10;
    Boolean noVirus = null;
    Boolean noAds = null;
    Boolean official = null;
    List<App> list = appDao.list(catalog, subCatalog, sort, order, currentPage, pageSize, noAds, noVirus, official);
    assertNotNull(list);
    assertTrue(list.size() > 0);
    App a = list.get(0);
    logger.info("Id:{}", a.getId());
    Session session = sessions.openSession();
    int delta = 9;
    int rows = appDao.updateIncrementDownload(session, a.getId(), delta);
    session.flush();
    assertTrue(rows > 0);
    rows = appDao.updateIncrementDownload(session, a.getId(), -delta);
    session.flush();
    session.close();
}
 
Example 25
Project: Equella   File: QtiAssessmentItemRefDaoImpl.java   View source code 6 votes vote down vote up
@Override
public QtiAssessmentItemRef getByUuid(final String uuid)
{
	final QtiAssessmentItemRef question = (QtiAssessmentItemRef) getHibernateTemplate()
		.execute(new TLEHibernateCallback()
		{
			@Override
			public Object doInHibernate(Session session) throws HibernateException
			{
				final Criteria criteria = createCriteria(session).createAlias("test", "t")
					.add(Restrictions.eq("t.institution", CurrentInstitution.get()))
					.add(Restrictions.eq("uuid", uuid));
				return criteria.uniqueResult();
			}
		});
	if( question == null )
	{
		throw new NotFoundException("Cannot find assessment item with uuid " + uuid);
	}
	return question;
}
 
Example 26
Project: hibernate-ogm-redis   File: RedisTestHelper.java   View source code 5 votes vote down vote up
@Override
public Map<String, Object> extractEntityTuple(Session session, EntityKey key) {
	RedisDatastoreProvider castProvider = getProvider( session.getSessionFactory() );
	AbstractRedisDialect gridDialect = getGridDialect( castProvider );

	if ( gridDialect instanceof RedisJsonDialect ) {
		return extractFromJsonDialect( key, (RedisJsonDialect) gridDialect );
	}

	if ( gridDialect instanceof RedisHashDialect ) {
		return extractFromHashDialect( session.getSessionFactory(), key, (RedisHashDialect) gridDialect );
	}

	throw new IllegalStateException( "Unsupported dialect " + gridDialect );
}
 
Example 27
Project: Equella   File: TermDaoImpl.java   View source code 5 votes vote down vote up
@Override
public List<TermResult> getRootTermResults(final Taxonomy taxonomy)
{
	return getHibernateTemplate().executeFind(new HibernateCallback()
	{
		@Override
		public Object doInHibernate(Session session)
		{
			Query q = session.createQuery(ROOT_TERM_RESULTS_QUERY);
			q.setParameter(0, taxonomy);
			q.setResultTransformer(TERM_RESULT_TRANSFORMER);
			return q.list();
		}
	});
}
 
Example 28
Project: lams   File: HibernateAccessor.java   View source code 5 votes vote down vote up
/**
 * Flush the given Hibernate Session if necessary.
 * @param session the current Hibernate Session
 * @param existingTransaction if executing within an existing transaction
 * @throws HibernateException in case of Hibernate flushing errors
 */
protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException {
	if (getFlushMode() == FLUSH_EAGER || (!existingTransaction && getFlushMode() != FLUSH_NEVER)) {
		logger.debug("Eagerly flushing Hibernate session");
		session.flush();
	}
}
 
Example 29
Project: sjk   File: AppDaoImpl.java   View source code 5 votes vote down vote up
@Override
public int updateHide(Session sess, List<Integer> ids) {
    String hql = "update App set Hidden = 1 where id in (:ids)";
    Query query = sess.createQuery(hql);
    query.setParameterList("ids", ids);
    int num = query.executeUpdate();
    if (ids != null && ids.size() == num) {
        appHistory4IndexDaoImpl.updateAppStatus2Del(ids);
    }
    return num;
}
 
Example 30
Project: Homework   File: MasterServiceImpl.java   View source code 5 votes vote down vote up
@Override
public boolean login(Master master, Session session, Transaction tx)
{
    MasterDao masterDao = new MasterDaoImpl();
    if (masterDao.findMaster(master, session, tx) == 0)
    {
        LOGGER.info("登陆失败");
        return false;
    }

    LOGGER.info("登陆成功");
    return true;
}
 
Example 31
Project: Hibernate_Association_Mapping_MAP_OneToMany_Save_Delete_Maven   File: HibernateUtil.java   View source code 5 votes vote down vote up
public static Session getSession(){
	Session session=null;
	if(threadLocal.get()==null){
	  session=factory.openSession();
	  threadLocal.set(session);
	}
	else{
		session=threadLocal.get();
	}
	return session;
	
}
 
Example 32
Project: sjk   File: MergeServiceImpl.java   View source code 5 votes vote down vote up
public void mergePaginationToApp(Session session, List<MarketApp> marketApps) {
    if (marketApps == null || marketApps.isEmpty()) {
        return;
    }
    int count = 0;
    List<MarketApp> exceptionApps = new ArrayList<MarketApp>();
    for (MarketApp mApp : marketApps) {
        try {
            if (++count % AppConfig.BATCH_SIZE == 0) {
                session.flush();
            }
            do1App(mApp, session);
        } catch (Exception e) {
            session.clear();
            exceptionApps.add(mApp);
            dbExceptionAppLogger.error(mApp.toString());
            if (e instanceof org.hibernate.NonUniqueObjectException) {
                dbExceptionAppLogger.error("The reduplicated entity.");
            } else {
                dbExceptionAppLogger.error("Exception", e);
            }
        }
    }
    // do again
    if (!exceptionApps.isEmpty()) {
        session.clear();
        marketApps.removeAll(exceptionApps);
        exceptionApps.clear();
        exceptionApps = null;
        mergePaginationToApp(session, marketApps);
    } else {
        session.flush();
    }
}
 
Example 33
Project: unitimes   File: TimetableManagerEditAction.java   View source code 5 votes vote down vote up
/**
 * Delete Manager
 * @param request
 * @param frm
 */
private void deleteManager(
        HttpServletRequest request, TimetableManagerForm frm ) {
	
	sessionContext.checkPermission(frm.getUniqueId(), "TimetableManager", Right.TimetableManagerEdit);
    
    TimetableManagerDAO mgrDao = new TimetableManagerDAO();
    Session hibSession = mgrDao.getSession();
    TimetableManager mgr = mgrDao.get(new Long(frm.getUniqueId()));

    Transaction tx = hibSession.beginTransaction();
   	
    ChangeLog.addChange(
            hibSession, 
            sessionContext, 
            mgr, 
            ChangeLog.Source.MANAGER_EDIT, 
            ChangeLog.Operation.DELETE, 
            null, 
            null);

    Set mgrRoles = mgr.getManagerRoles();
   	for (Iterator i=mgrRoles.iterator(); i.hasNext(); ) {
   	    ManagerRole mgrRole = (ManagerRole) i.next();
   	    hibSession.delete(mgrRole);
   	}
   	for (Department d: mgr.getDepartments()) {
   		d.getTimetableManagers().remove(mgr);
   		hibSession.saveOrUpdate(d);
   	}
   	for (SolverGroup sg: mgr.getSolverGroups()) {
   		sg.getTimetableManagers().remove(mgr);
   		hibSession.saveOrUpdate(sg);
   	}

    hibSession.delete(mgr);

   	tx.commit();
}
 
Example 34
Project: maven_EWorld_OpenShift   File: Fetch.java   View source code 5 votes vote down vote up
synchronized public static Places getPlaceFromDesc(String desc)
{
         Places pl = null;
         int chk=0;
         sf=Logic.getSf();
         Session s = null;
         try{
                s=sf.openSession();
                s.beginTransaction();
                Query qry=s.createQuery("from Places pl where pl.pl_desc=:pldesc");
                qry.setParameter("pldesc", desc);
                pl=(Places)qry.getSingleResult();
                s.getTransaction().commit();
            }catch (Exception e)
                 {
                         chk=-1;
                         System.out.println("HibernateException Occured!!"+e);
                         e.printStackTrace();
                 }
            finally
                 {
                         if(s!=null)
                         {
                              s.clear();
                              s.close();
                         }
                 }
            if(chk==0)
            {
                 return (pl);
            }
            else
            {
                 return (new Places());
            }
}
 
Example 35
Project: bdf2   File: CalendarMaintain.java   View source code 5 votes vote down vote up
@DataResolver
public void saveCalendars(Collection<JobCalendar> calendars){
	SessionFactory sessionFactory=this.getSessionFactory();
	Session session=sessionFactory.openSession();
	try{
		for(JobCalendar c:calendars){
			EntityState state=EntityUtils.getState(c);
			if(state.equals(EntityState.NEW)){
				c.setId(UUID.randomUUID().toString());
				c.setCompanyId(dataService.getCompanyId());
				session.save(c);
			}
			if(state.equals(EntityState.MODIFIED)){
				session.update(c);
			}
			if(state.equals(EntityState.DELETED)){
				String hql="select count(*) from "+JobCalendarRelation.class.getName()+" where calendarId=:calendarId";
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("calendarId", c.getId());
				int count=this.queryForInt(hql, map);
				if(count>0){
					throw new RuntimeException("当前日期有Job正在使用,不能被删除");
				}
				hql="delete "+JobCalendarDate.class.getName()+" where calendarId=:calendarId";
				session.createQuery(hql).setString("calendarId", c.getId()).executeUpdate();
				session.delete(c);
			}
			if(c.getCalendarDates()!=null){
				this.saveCalendarDates(c.getCalendarDates(), session);
			}
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 36
Project: sdudoc   File: CollectDaoImpl.java   View source code 5 votes vote down vote up
@Override
public List<String> getRecommend(int userId) {
	String sql = "select b.dynasty from Collect c, Book b where c.bookId = b.bookID and c.userId=:userId group by b.dynasty having" +
			" count(c.bookId) >= all (select count(c1.bookId) from Collect c1, Book b1 where c1.bookId = b1.bookID and c1.userId=:userId1 group by b1.dynasty)";
	Session session = sessionFactory.getCurrentSession();
	Query query = session.createQuery(sql);
	query.setInteger("userId", userId);
	query.setInteger("userId1", userId);
	return query.list();
}
 
Example 37
Project: OSWf-OSWorkflow-fork   File: HibernatePersistentVarsDAO.java   View source code 5 votes vote down vote up
public void save(HibernatePersistentVarsItem item) {

        if( item == null)
            throw new PersistentVarsException("Could not save 'null' PropertyItem");
 
       Session session = null;
       Transaction transaction = null;

        try {
            session = this.sessionFactory.openSession();
            transaction = session.beginTransaction();
            
            session.saveOrUpdate(item);
            session.flush();
            
            transaction.commit();
            
        } catch (HibernateException hibernateException) {
            throw new PersistentVarsException("Could not save key '" + item.getKey() + "':" + hibernateException.getMessage());
        } finally {
            
            if (transaction != null && transaction.isActive())
                 transaction.rollback();

            if (session != null)
                session.close();
        }
    }
 
Example 38
Project: JavaEE   File: App.java   View source code 5 votes vote down vote up
/**
 * Creating a session
 * @return org.hibernate.Session
 */
private Session createHibernateSession() {
    try {
        Map<String, String> settings = new HashMap<String, String>();
        settings.put("hibernate.connection.driver_class", "org.sqlite.JDBC");
        settings.put("hibernate.connection.url", "jdbc:sqlite:mysqlite.db");
        settings.put("hibernate.connection.username", "");
        settings.put("hibernate.connection.password", "");
        settings.put("hibernate.show_sql", "true");
        settings.put("hibernate.hbm2ddl.auto", "update");

        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .applySettings(settings)
                .build();

        MetadataSources sources = new MetadataSources(registry)
                .addAnnotatedClass(Person.class);

        Metadata metadata = sources
                .getMetadataBuilder()
                .build();

        SessionFactory sessionFactory = metadata
                .getSessionFactoryBuilder()
                .build();

        session = sessionFactory.openSession();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }
    System.out.println("Session created successfully.");
    return session;
}
 
Example 39
Project: bdf2   File: HibernateDao.java   View source code 5 votes vote down vote up
public Collection<?> query(DetachedCriteria detachedCriteria,String dataSourceName){
	Session session=this.getSessionFactory(dataSourceName).openSession();
	try{
		return detachedCriteria.getExecutableCriteria(session).list();
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 40
Project: sbc-qsystem   File: Spring.java   View source code 5 votes vote down vote up
public void saveOrUpdateAll(Collection list) {
    final Session ses = getTxManager().getSessionFactory().getCurrentSession();
    list.stream().forEach((object) -> {
        ses.saveOrUpdate(object);
    });
    ses.flush();
}