@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; }
@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; }
@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); } } }
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(); }
@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); }
@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(); } }); }
@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; }
@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); }
@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; }
@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(); } }
@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; }
@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; }
@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; }
@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; }
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; }
@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; }
@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(); } }
@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); } }
@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; }
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 (); } }); }
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; } }); }
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); }
@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(); }
@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; }
@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 ); }
@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(); } }); }
/** * 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(); } }
@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; }
@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; }
public static Session getSession(){ Session session=null; if(threadLocal.get()==null){ session=factory.openSession(); threadLocal.set(session); } else{ session=threadLocal.get(); } return session; }
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(); } }
/** * 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(); }
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()); } }
@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(); } }
@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(); }
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(); } }
/** * 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; }
public Collection<?> query(DetachedCriteria detachedCriteria,String dataSourceName){ Session session=this.getSessionFactory(dataSourceName).openSession(); try{ return detachedCriteria.getExecutableCriteria(session).list(); }finally{ session.flush(); session.close(); } }
public void saveOrUpdateAll(Collection list) { final Session ses = getTxManager().getSessionFactory().getCurrentSession(); list.stream().forEach((object) -> { ses.saveOrUpdate(object); }); ses.flush(); }
@Override public User findByPrimary(Long id) { User user = null; Session session = sessionFactory.getCurrentSession(); try { session.beginTransaction(); user = session.get(User.class, id); session.getTransaction().commit(); } catch (RuntimeException e) { session.getTransaction().rollback(); } return user; }