Example usage for org.hibernate FlushMode MANUAL

List of usage examples for org.hibernate FlushMode MANUAL

Introduction

In this page you can find the example usage for org.hibernate FlushMode MANUAL.

Prototype

FlushMode MANUAL

To view the source code for org.hibernate FlushMode MANUAL.

Click Source Link

Document

The Session is only ever flushed when Session#flush is explicitly called by the application.

Usage

From source file:org.unitime.timetable.action.CrossListsModifyAction.java

License:Open Source License

/**
 * Update the instructional offering//from  w  ww .  j a  v  a2s. co m
 * @param request
 * @param frm
 */
private void doUpdate(HttpServletRequest request, CrossListsModifyForm frm) throws Exception {

    // Get the modified offering
    List ids = frm.getCourseOfferingIds();
    String courseIds = Constants.arrayToStr(ids.toArray(), "", " ");
    String origCourseIds = frm.getOriginalOfferings();

    // Get Offering
    CourseOfferingDAO cdao = new CourseOfferingDAO();
    InstructionalOfferingDAO idao = new InstructionalOfferingDAO();
    InstructionalOffering io = idao.get(frm.getInstrOfferingId());
    Session hibSession = idao.getSession();
    hibSession.setFlushMode(FlushMode.MANUAL);
    Transaction tx = null;
    HashMap saList = new HashMap();
    List<CurriculumCourse> cc = new ArrayList<CurriculumCourse>();

    try {
        tx = hibSession.beginTransaction();
        StringTokenizer strTok = new StringTokenizer(origCourseIds);

        while (strTok.hasMoreTokens()) {

            String origCrs = strTok.nextToken();

            // 1. For all deleted courses - create new offering and make 'not offered'
            if (courseIds.indexOf(origCrs) < 0) {
                Debug.debug("Course removed from offering: " + origCrs);

                // Create new instructional offering 
                InstructionalOffering io1 = new InstructionalOffering();
                CourseOffering co1 = cdao.get(new Long(origCrs.trim()));

                // Copy attributes of old instr offering - make not offered
                io1.setDemand(io.getDemand());
                io1.setLimit(io.getLimit());
                io1.setNotOffered(new Boolean(true));
                io1.setSession(io.getSession());
                io1.setByReservationOnly(io.getByReservationOnly());

                // Copy attributes of old crs offering - set controlling                   
                CourseOffering co2 = (CourseOffering) co1.clone();
                co2.setIsControl(new Boolean(true));

                for (CurriculumCourse x : (List<CurriculumCourse>) hibSession
                        .createQuery("from CurriculumCourse where course.uniqueId = :courseId")
                        .setLong("courseId", co1.getUniqueId()).list()) {
                    cc.add(x.clone(co2));
                    x.getClassification().getCourses().remove(x);
                    hibSession.delete(x);
                }

                /*                   
                                   hibSession.saveOrUpdate(io1);
                                   hibSession.flush();
                */
                // Remove from original inst offr
                Set offerings = io.getCourseOfferings();
                for (Iterator i = offerings.iterator(); i.hasNext();) {

                    CourseOffering co3 = (CourseOffering) i.next();
                    if (co3.equals(co1)) {
                        // Remove from Subject Area
                        SubjectArea sa = co3.getSubjectArea();
                        sa.getCourseOfferings().remove(co1);
                        hibSession.saveOrUpdate(sa);
                        saList.put(sa.getSubjectAreaAbbreviation(), sa);
                    }
                }

                // Delete old course offering
                io.removeCourseOffering(co1);

                Event.deleteFromEvents(hibSession, co1);
                Exam.deleteFromExams(hibSession, co1);

                String className = ApplicationProperty.ExternalActionCourseOfferingRemove.value();
                if (className != null && className.trim().length() > 0) {
                    ExternalCourseOfferingRemoveAction removeAction = (ExternalCourseOfferingRemoveAction) (Class
                            .forName(className).newInstance());
                    removeAction.performExternalCourseOfferingRemoveAction(co1, hibSession);
                }
                hibSession.delete(co1);

                //io.setCourseOfferings(offerings);

                hibSession.saveOrUpdate(io);
                hibSession.flush();

                // Add course to instructional offering
                co2.setInstructionalOffering(io1);
                io1.addTocourseOfferings(co2);

                // Update
                if (io1.getInstrOfferingPermId() == null)
                    io1.generateInstrOfferingPermId();
                hibSession.saveOrUpdate(io1);
                hibSession.flush();

                hibSession.refresh(io);
                hibSession.refresh(io1);
                className = ApplicationProperty.ExternalActionInstructionalOfferingInCrosslistAdd.value();
                if (className != null && className.trim().length() > 0) {
                    ExternalInstructionalOfferingInCrosslistAddAction addAction = (ExternalInstructionalOfferingInCrosslistAddAction) (Class
                            .forName(className).newInstance());
                    addAction.performExternalInstructionalOfferingInCrosslistAddAction(io1, hibSession);
                }
            }

            // 2. For all existing courses - update controlling attribute and reservation limits
            else {
                Debug.debug("Updating controlling course  and course reservation: " + origCrs);

                // Update controlling course attribute
                CourseOffering co = cdao.get(new Long(origCrs));
                if (frm.getCtrlCrsOfferingId().equals(co.getUniqueId()))
                    co.setIsControl(new Boolean(true));
                else
                    co.setIsControl(new Boolean(false));

                // Update course reservation
                int indx = frm.getIndex(origCrs);
                try {
                    co.setReservation(ids.size() > 1 ? Integer.valueOf(frm.getLimits(indx)) : null);
                } catch (NumberFormatException e) {
                    co.setReservation(null);
                }

                hibSession.saveOrUpdate(co);

                hibSession.flush();
                hibSession.refresh(co);
            }
        }

        // 3. For all added courses - delete all preferences and change the instr offering id  
        Vector addedOfferings = new Vector();
        StringTokenizer strTok2 = new StringTokenizer(courseIds);

        while (strTok2.hasMoreTokens()) {
            String course = strTok2.nextToken();

            // Course added to offering
            if (origCourseIds.indexOf(course) < 0) {

                Debug.debug("Course added to offering: " + course);

                CourseOffering co1 = cdao.get(new Long(course.trim()));
                InstructionalOffering io1 = co1.getInstructionalOffering();
                SubjectArea sa = io1.getControllingCourseOffering().getSubjectArea();
                Set offerings = io1.getCourseOfferings();

                // Copy course offerings
                for (Iterator i = offerings.iterator(); i.hasNext();) {
                    CourseOffering co2 = (CourseOffering) i.next();
                    SubjectArea sa2 = co2.getSubjectArea();

                    // Create a copy
                    CourseOffering co3 = (CourseOffering) co2.clone();
                    if (frm.getCtrlCrsOfferingId().equals(co2.getUniqueId()))
                        co3.setIsControl(new Boolean(true));
                    else
                        co3.setIsControl(new Boolean(false));

                    for (CurriculumCourse x : (List<CurriculumCourse>) hibSession
                            .createQuery("from CurriculumCourse where course.uniqueId = :courseId")
                            .setLong("courseId", co2.getUniqueId()).list()) {
                        cc.add(x.clone(co3));
                        x.getClassification().getCourses().remove(x);
                        hibSession.delete(x);
                    }

                    addedOfferings.addElement(co3);

                    int indx = frm.getIndex(course);
                    try {
                        co3.setReservation(Integer.valueOf(frm.getLimits(indx)));
                    } catch (NumberFormatException e) {
                        co3.setReservation(null);
                    }

                    // Remove from collection
                    //i.remove();

                    sa2.getCourseOfferings().remove(co2);
                    hibSession.saveOrUpdate(sa2);
                    saList.put(sa2.getSubjectAreaAbbreviation(), sa2);

                    // Delete course offering
                    io1.removeCourseOffering(co2);
                    Event.deleteFromEvents(hibSession, co2);
                    Exam.deleteFromExams(hibSession, co2);
                    String className = ApplicationProperty.ExternalActionCourseOfferingRemove.value();
                    if (className != null && className.trim().length() > 0) {
                        ExternalCourseOfferingRemoveAction removeAction = (ExternalCourseOfferingRemoveAction) (Class
                                .forName(className).newInstance());
                        removeAction.performExternalCourseOfferingRemoveAction(co2, hibSession);
                    }

                    hibSession.delete(co2);
                    hibSession.flush();

                    //hibSession.refresh(sa2);

                }

                //io1.setCourseOfferings(offerings);
                //hibSession.saveOrUpdate(io1);
                Event.deleteFromEvents(hibSession, io1);
                Exam.deleteFromExams(hibSession, io1);

                hibSession.delete(io1);
                hibSession.flush();

                hibSession.saveOrUpdate(sa);
                saList.put(sa.getSubjectAreaAbbreviation(), sa);

                //hibSession.refresh(sa);

            }
        }

        hibSession.flush();

        // Update Offering - Added Offerings       
        for (int i = 0; i < addedOfferings.size(); i++) {
            CourseOffering co3 = (CourseOffering) addedOfferings.elementAt(i);
            co3.setInstructionalOffering(io);
            io.addTocourseOfferings(co3);
            hibSession.saveOrUpdate(co3);

            hibSession.flush();
            hibSession.refresh(co3);

            hibSession.saveOrUpdate(io);
        }
        for (CurriculumCourse x : cc)
            hibSession.saveOrUpdate(x);

        // Update managing department on all classes
        Department dept = io.getControllingCourseOffering().getDepartment();
        Set cfgs = io.getInstrOfferingConfigs();
        for (Iterator iterCfg = cfgs.iterator(); iterCfg.hasNext();) {
            InstrOfferingConfig cfg = (InstrOfferingConfig) iterCfg.next();
            Set subparts = cfg.getSchedulingSubparts();
            for (Iterator iterSbp = subparts.iterator(); iterSbp.hasNext();) {
                SchedulingSubpart subpart = (SchedulingSubpart) iterSbp.next();
                Set classes = subpart.getClasses();
                for (Iterator iterCls = classes.iterator(); iterCls.hasNext();) {
                    Class_ cls = (Class_) iterCls.next();
                    // Only change departmental class managing dept and not externally managed
                    if (!cls.getManagingDept().isExternalManager()) {
                        cls.setManagingDept(dept);
                        hibSession.saveOrUpdate(cls);
                    }
                }
            }
        }

        ChangeLog.addChange(hibSession, sessionContext, io, ChangeLog.Source.CROSS_LIST,
                ChangeLog.Operation.UPDATE, io.getControllingCourseOffering().getSubjectArea(), null);

        tx.commit();
        hibSession.flush();
        hibSession.clear();
        hibSession.refresh(io);

        // Refresh objects
        for (Iterator i1 = io.getInstrOfferingConfigs().iterator(); i1.hasNext();) {
            InstrOfferingConfig cfg = (InstrOfferingConfig) i1.next();
            for (Iterator i2 = cfg.getSchedulingSubparts().iterator(); i2.hasNext();) {
                SchedulingSubpart ss = (SchedulingSubpart) i2.next();
                for (Iterator i3 = ss.getClasses().iterator(); i3.hasNext();) {
                    Class_ c = (Class_) i3.next();
                    hibSession.refresh(c);
                }
                hibSession.refresh(ss);
            }
        }

        Set keys = saList.keySet();
        for (Iterator i1 = keys.iterator(); i1.hasNext();) {
            hibSession.refresh(saList.get(i1.next()));
        }
        String className = ApplicationProperty.ExternalActionCourseCrosslist.value();
        if (className != null && className.trim().length() > 0) {
            ExternalCourseCrosslistAction addAction = (ExternalCourseCrosslistAction) (Class.forName(className)
                    .newInstance());
            addAction.performExternalCourseCrosslistAction(io, hibSession);
        }

    } catch (Exception e) {
        Debug.error(e);
        try {
            if (tx != null && tx.isActive())
                tx.rollback();
        } catch (Exception e1) {
        }
        throw e;
    }
}

From source file:org.unitime.timetable.backup.SessionRestore.java

License:Open Source License

public void restore(InputStream input, Progress progress)
        throws IOException, InstantiationException, IllegalAccessException, DocumentException {
    iIn = input;//from w w  w.java 2s  .c om
    iProgress = progress;
    iHibSession = new _RootDAO().createNewSession();
    iHibSession.setCacheMode(CacheMode.IGNORE);
    iHibSessionFactory = iHibSession.getSessionFactory();
    try {
        CodedInputStream cin = CodedInputStream.newInstance(iIn);
        cin.setSizeLimit(1024 * 1024 * 1024); // 1 GB

        iProgress.setPhase("Loading data", 1);
        TableData.Table t = null;
        while ((t = readTable(cin)) != null) {
            if (iDebug != null) {
                iDebug.println("## " + t.getName() + " ##");
                iDebug.print(t.toString());
                iDebug.flush();
            }
            create(t);
        }
        iProgress.incProgress();

        iHibSession.setFlushMode(FlushMode.MANUAL);
        iProgress.setPhase("Fixing", iAllEntitites.size());
        for (Iterator<Entity> i = iAllEntitites.iterator(); i.hasNext();) {
            iProgress.incProgress();
            if (!fix(i.next()))
                i.remove();
        }

        iProgress.setPhase("Saving (not-null)", iAllEntitites.size());
        List<Entity> save = new ArrayList<Entity>(iAllEntitites);
        boolean saved = true;
        while (!save.isEmpty() && saved) {
            saved = false;
            for (Iterator<Entity> i = save.iterator(); i.hasNext();) {
                Entity e = i.next();
                if (e.canSave() == null) {
                    iProgress.incProgress();
                    e.fixRelationsNullOnly();
                    iHibSession.save(e.getObject());
                    i.remove();
                    saved = true;
                }
            }
            iHibSession.flush();
        }

        iProgress.setPhase("Saving (all)", iAllEntitites.size());
        for (Entity e : iAllEntitites) {
            iProgress.incProgress();
            String property = e.canSave();
            if (property == null) {
                e.fixRelations();
                iHibSession.update(e.getObject());
            } else {
                message("Skipping " + e.getAbbv() + " (missing not-null relation " + property + ")", e.getId());
                continue;
            }
        }

        iProgress.setPhase("Flush", 1);
        iHibSession.flush();
        iProgress.incProgress();

        printMessages();

        iProgress.setStatus("All done.");
    } finally {
        iHibSession.close();
    }
}

From source file:org.unitime.timetable.dataexchange.BaseCourseOfferingImport.java

License:Open Source License

private InstructionalOffering findInstrOffrForExternalId(String externalId, Long sessionId) {
    return (InstructionalOffering) this.getHibSession().createQuery(
            "select distinct io from InstructionalOffering as io where io.externalUniqueId=:externalId and io.session.uniqueId=:sessionId")
            .setLong("sessionId", sessionId.longValue()).setString("externalId", externalId).setCacheable(true)
            .setFlushMode(FlushMode.MANUAL).uniqueResult();
}

From source file:org.unitime.timetable.dataexchange.EventImport.java

License:Open Source License

private Room findRoom(String buildingAbbv, String roomNumber) {
    Room room = null;/*  ww  w . ja va  2 s  .com*/
    if (room == null) {
        List rooms = this.getHibSession().createQuery(
                "select distinct r from Room as r where r.roomNumber=:roomNbr and r.building.abbreviation = :building")
                .setString("building", buildingAbbv).setString("roomNbr", roomNumber).setCacheable(true)
                .setFlushMode(FlushMode.MANUAL).list();
        if (rooms != null && rooms.size() > 0) {
            room = (Room) rooms.iterator().next();
        }
    }
    return (room);
}

From source file:org.unitime.timetable.dataexchange.EventImport.java

License:Open Source License

private SponsoringOrganization findSponsoringOrg(String name) {
    SponsoringOrganization sponsoringOrg = null;
    if (sponsoringOrg == null) {
        sponsoringOrg = (SponsoringOrganization) this.getHibSession()
                .createQuery("select distinct so from SponsoringOrganization as so where so.name = :name")
                .setString("name", name).setCacheable(true).setFlushMode(FlushMode.MANUAL).uniqueResult();
    }/*w w  w  .j a  va 2  s  . com*/
    return (sponsoringOrg);
}

From source file:org.unitime.timetable.model.Class_.java

License:Open Source License

public static List findAllForControllingSubjectArea(String subjectAreaAbbv, Long sessionId,
        org.hibernate.Session hibSession) {
    return hibSession.createQuery(
            "select distinct c from Class_ c inner join c.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as co where "
                    + "co.subjectArea.subjectAreaAbbreviation=:subjectAreaAbbv and c.schedulingSubpart.instrOfferingConfig.instructionalOffering.session.uniqueId=:sessionId and co.isControl=1")
            .setString("subjectAreaAbbv", subjectAreaAbbv).setLong("sessionId", sessionId.longValue())
            .setFlushMode(FlushMode.MANUAL).list();
}

From source file:org.unitime.timetable.model.Department.java

License:Open Source License

/**
 * /*from   w w w .j a v a  2  s .c  o m*/
 * @param deptCode
 * @param sessionId
 * @param hibSession
 * @return
 * @throws Exception
 */
public static Department findByDeptCode(String deptCode, Long sessionId, org.hibernate.Session hibSession) {
    return (Department) hibSession.createQuery(
            "select distinct d from Department as d where d.deptCode=:deptCode and d.session.uniqueId=:sessionId")
            .setLong("sessionId", sessionId).setString("deptCode", deptCode).setCacheable(true)
            .setFlushMode(FlushMode.MANUAL).uniqueResult();
}

From source file:org.unitime.timetable.model.Department.java

License:Open Source License

public Department findSameDepartmentInSession(Long newSessionId, org.hibernate.Session hibSession) {
    if (newSessionId == null) {
        return (null);
    }// w w  w.  java 2  s  . c om
    Department newDept = Department.findByDeptCode(this.getDeptCode(), newSessionId, hibSession);
    if (newDept == null && this.getExternalUniqueId() != null) {
        // if a department wasn't found and an external uniqueid exists for this 
        //   department check to see if the new term has a department that matches 
        //   the external unique id
        List l = hibSession.createCriteria(Department.class)
                .add(Restrictions.eq("externalUniqueId", this.getExternalUniqueId()))
                .add(Restrictions.eq("session.uniqueId", newSessionId)).setFlushMode(FlushMode.MANUAL)
                .setCacheable(true).list();

        if (l.size() == 1) {
            newDept = (Department) l.get(0);
        }
    }
    return (newDept);
}

From source file:org.unitime.timetable.model.DepartmentalInstructor.java

License:Open Source License

public static DepartmentalInstructor findByPuidDepartmentId(String puid, Long deptId,
        org.hibernate.Session hibSession) {
    try {// w w w  . j  a  v  a  2s. c  om
        return (DepartmentalInstructor) hibSession.createQuery(
                "select d from DepartmentalInstructor d where d.externalUniqueId=:puid and d.department.uniqueId=:deptId")
                .setString("puid", puid).setLong("deptId", deptId.longValue()).setCacheable(true)
                .setFlushMode(FlushMode.MANUAL).uniqueResult();
    } catch (NonUniqueResultException e) {
        Debug.warning("There are two or more instructors with puid " + puid + " for department " + deptId
                + " -- returning the first one.");
        return (DepartmentalInstructor) hibSession.createQuery(
                "select d from DepartmentalInstructor d where d.externalUniqueId=:puid and d.department.uniqueId=:deptId")
                .setString("puid", puid).setLong("deptId", deptId.longValue()).setCacheable(true)
                .setFlushMode(FlushMode.MANUAL).list().get(0);
    }
}

From source file:org.unitime.timetable.model.EventContact.java

License:Open Source License

public static EventContact findByExternalUniqueId(String externalUniqueId) {
    return (EventContact) new EventContactDAO().getSession()
            .createQuery("select c from EventContact c where c.externalUniqueId=:externalUniqueId")
            .setString("externalUniqueId", externalUniqueId).setFlushMode(FlushMode.MANUAL).uniqueResult();
}