Example usage for org.hibernate Session merge

List of usage examples for org.hibernate Session merge

Introduction

In this page you can find the example usage for org.hibernate Session merge.

Prototype

Object merge(Object object);

Source Link

Document

Copy the state of the given object onto the persistent object with the same identifier.

Usage

From source file:ome.logic.UpdateImpl.java

License:Open Source License

/**
 * Note if we use anything other than merge here, functionality from
 * {@link ome.tools.hibernate.MergeEventListener} needs to be moved to
 * {@link UpdateFilter} or to another event listener.
 *//*w  w w . j ava  2 s.  c  o  m*/
protected IObject internalMerge(IObject obj, UpdateFilter filter, Session session) {
    if (getBeanHelper().getLogger().isDebugEnabled()) {
        getBeanHelper().getLogger().debug(" Internal merge. ");
    }

    IObject result = (IObject) filter.filter(null, obj);
    result = (IObject) session.merge(result);
    return result;
}

From source file:ome.security.auth.SimpleRoleProvider.java

License:Open Source License

public long createGroup(String name, Permissions perms, boolean strict) {
    Session s = sf.getSession();
    ExperimenterGroup g = groupByName(name, s);

    if (g == null) {
        g = new ExperimenterGroup();
        g.setName(name);/*from   w w w.  j  av  a 2  s .  co  m*/
        if (perms == null) {
            perms = Permissions.USER_PRIVATE; // ticket:1434
        }
        g.getDetails().setPermissions(perms);
        g = (ExperimenterGroup) s.merge(g);
    } else {
        if (strict) {
            throw new ValidationException("Group already exists: " + name);
        }
    }
    return g.getId();
}

From source file:ome.services.sharing.BlobShareStore.java

License:Open Source License

@Override
public void doSet(Share share, ShareData data, List<ShareItem> items) {

    long oldOptLock = data.optlock;
    long newOptLock = oldOptLock + 1;
    Session session = session();

    List list = session//from w  w w .  ja  v a 2 s.co m
            .createQuery("select s from Share s where s.id = " + data.id + " and s.version =" + data.optlock)
            .list();

    if (list.size() == 0) {
        throw new OptimisticLockException("Share " + data.id + " has been updated by someone else.");
    }

    data.optlock = newOptLock;
    share.setData(parse(data));
    share.setActive(data.enabled);
    share.setItemCount((long) items.size());
    share.setVersion((int) newOptLock);
    session.merge(share);
    synchronizeMembers(session, data);
}

From source file:ome.services.sharing.BlobShareStore.java

License:Open Source License

private void synchronizeMembers(Session session, ShareData data) {

    Query q = session.createQuery("select sm from ShareMember sm " + "where sm.parent = ?");
    q.setLong(0, data.id);/*from  ww w .  j a v  a 2s. c o m*/
    List<ShareMember> members = q.list();
    Map<Long, ShareMember> lookup = new HashMap<Long, ShareMember>();
    for (ShareMember sm : members) {
        lookup.put(sm.getChild().getId(), sm);
    }

    Set<Long> intendedUserIds = new HashSet<Long>(data.members);
    intendedUserIds.add(data.owner);

    Set<Long> currentUserIds = lookup.keySet();

    Set<Long> added = new HashSet<Long>(intendedUserIds);
    added.removeAll(currentUserIds);
    for (Long toAdd : added) {
        ShareMember sm = new ShareMember();
        sm.link(new Share(data.id, false), new Experimenter(toAdd, false));
        session.merge(sm);
    }

    Set<Long> removed = new HashSet<Long>(currentUserIds);
    removed.removeAll(intendedUserIds);
    for (Long toRemove : removed) {
        session.delete(lookup.get(toRemove));
    }

}

From source file:onl.netfishers.netshot.work.tasks.CheckComplianceTask.java

License:Open Source License

@Override
public void run() {
    logger.debug("Starting check compliance task for device {}.", device.getId());
    this.logIt(String.format("Check compliance task for device %s (%s).", device.getName(),
            device.getMgmtAddress().getIp()), 5);

    Session session = Database.getSession();
    try {//from w  w w .j a  v  a 2  s  .  c  om
        session.beginTransaction();
        session.createQuery("delete from CheckResult c where c.key.device.id = :id")
                .setLong("id", this.device.getId()).executeUpdate();
        session.evict(this.device);
        Device device = (Device) session.createQuery("from Device d join fetch d.lastConfig where d.id = :id")
                .setLong("id", this.device.getId()).uniqueResult();
        if (device == null) {
            logger.info(
                    "Unable to fetch the device with its last config... has it been captured at least once?");
            throw new Exception("No last config for this device. Has it been captured at least once?");
        }
        @SuppressWarnings("unchecked")
        List<Policy> policies = session
                .createQuery(
                        "select p from Policy p join p.targetGroup g join g.cachedDevices d where d.id = :id")
                .setLong("id", this.device.getId()).list();

        for (Policy policy : policies) {
            policy.check(device, session);
            session.merge(policy);
        }
        @SuppressWarnings("unchecked")
        List<SoftwareRule> softwareRules = session.createCriteria(SoftwareRule.class)
                .addOrder(Property.forName("priority").asc()).list();
        device.setSoftwareLevel(ConformanceLevel.UNKNOWN);
        for (SoftwareRule rule : softwareRules) {
            rule.check(device);
            if (device.getSoftwareLevel() != ConformanceLevel.UNKNOWN) {
                break;
            }
        }
        @SuppressWarnings("unchecked")
        List<HardwareRule> hardwareRules = session.createCriteria(HardwareRule.class).list();
        device.resetEoX();
        for (HardwareRule rule : hardwareRules) {
            rule.check(device);
        }
        session.merge(device);
        session.getTransaction().commit();
        this.status = Status.SUCCESS;
    } catch (Exception e) {
        session.getTransaction().rollback();
        logger.error("Error while checking compliance.", e);
        this.logIt("Error while checking compliance: " + e.getMessage(), 2);
        this.status = Status.FAILURE;
        return;
    } finally {
        session.close();
    }

}

From source file:openones.oopms.planner.dao.ModuleDAO.java

License:Apache License

/**
 * Update Plan size, actual size, plan size unit, actual size unit and status of module after creating new task.
 * @param task/*from   w  w w.  j  av a 2  s. co  m*/
 */

public void updateModuleByTask(Tasks task) {
    log.debug("updateModuleByTask.START");
    Session session = null;
    Transaction tx = null;
    try {

        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();

        Module module = (Module) session.get(Module.class, task.getModule().getModuleId());
        if (module.getPlannedSize() == null)
            module.setPlannedSize(new BigDecimal(0));
        module.setPlannedSize(module.getPlannedSize().add(task.getProductsize()));

        if (module.getActualSize() == null)
            module.setActualSize(new BigDecimal(0));
        module.setActualSize(module.getActualSize().add(task.getCompletedsize()));

        module.setPlannedSizeUnitId(task.getSizeunit());
        module.setActualSizeUnitId(task.getSizeunit());
        List<BigDecimal> taskStatusList = getTasksStatusByModule(module.getModuleId());

        if (taskStatusList.size() == 0)
            module.setStatus(new BigDecimal(175));// 175: CANCEL
        else {
            Boolean flag = true;
            for (int i = 0; i < taskStatusList.size(); i++) {
                log.debug("Task status " + i + ": " + taskStatusList.get(i));
                if (!taskStatusList.get(0).equals(taskStatusList.get(i)))
                    flag = false;
                log.debug("Flag: " + flag);
            }
            if (flag.equals(true))
                module.setStatus(taskStatusList.get(0));
            else
                module.setStatus(new BigDecimal(173));// 173: ON-GOING

        }

        session.merge(module);
        log.debug("updateModuleByTask.END");
        log.debug("Task Product size: " + task.getProductsize());
        log.debug("Task Complete size: " + task.getCompletedsize());
        log.debug("Module plan: " + module.getPlannedSize());
        log.debug("Module actual: " + module.getActualSize());
        log.debug("Module status: " + module.getStatus());

        tx.commit();
    } catch (RuntimeException e) {
        try {
            tx.rollback();
        } catch (RuntimeException rbe) {
            log.error("Couldnt roll back transaction", rbe);
        }
        log.error("updateModuleByTask.ERROR", e);
    } finally {
        if (session != null) {
            session.close();
        }

    }
}

From source file:openones.oopms.planner.dao.ModuleDAO.java

License:Apache License

/**
 * update Plan size, actual size, plan size unit, actual size unit and status of module after updating new task.
 * @param task/*from   w w  w  .j  a  va 2  s . c  om*/
 * @param editedTask
 */

public void updateModuleByEditedTask(Tasks task, Tasks editedTask) {
    log.debug("updateModuleByEditedTask.START");
    Session session = null;
    Transaction tx = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();

        Module module = (Module) session.get(Module.class, editedTask.getModule().getModuleId());

        if (!task.getProductsize().equals(editedTask.getProductsize())) {
            module.setPlannedSize(
                    module.getPlannedSize().add(editedTask.getProductsize().subtract(task.getProductsize())));
        }
        if (!task.getCompletedsize().equals(editedTask.getCompletedsize())) {
            module.setActualSize(module.getActualSize()
                    .add(editedTask.getCompletedsize().subtract(task.getCompletedsize())));
        }

        module.setPlannedSizeUnitId(editedTask.getSizeunit());
        module.setActualSizeUnitId(editedTask.getSizeunit());

        if (!task.getStatusid().equals(editedTask.getStatusid())) {
            List<BigDecimal> taskStatusList = getTasksStatusByModule(module.getModuleId());
            if (taskStatusList.size() == 0)
                module.setStatus(new BigDecimal(175));// 175: CANCEL
            else {
                Boolean flag = true;
                for (int i = 0; i < taskStatusList.size(); i++) {
                    log.debug("Task status " + i + ": " + taskStatusList.get(i));
                    if (!taskStatusList.get(0).equals(taskStatusList.get(i)))
                        flag = false;
                    log.debug("Flag: " + flag);
                }
                if (flag.equals(true))
                    module.setStatus(taskStatusList.get(0));
                else
                    module.setStatus(new BigDecimal(173));// 173: ON-GOING
            }

        }

        session.merge(module);
        log.debug("updateModuleByEditedTask.END");
        log.debug("Task Product size: " + task.getProductsize());
        log.debug("Task Complete size: " + task.getCompletedsize());
        log.debug("Module plan: " + module.getPlannedSize());
        log.debug("Module actual: " + module.getActualSize());
        log.debug("Module status: " + module.getStatus());
        tx.commit();

    } catch (RuntimeException e) {
        try {
            tx.rollback();
        } catch (RuntimeException rbe) {
            log.error("Couldnt roll back transaction", rbe);
        }
        log.error("updateModuleByEditedTask.Exception", e);
    } finally {
        if (session != null) {
            session.close();
        }

    }

}

From source file:org.babyfish.test.hibernate.model.setandref.DbTest.java

License:Open Source License

@Test
public void testMergeDepartment() {
    final Ref<Employee> employeeRef = new Ref<Employee>();
    final Ref<Department> department2Ref = new Ref<Department>();
    Action<Session> handler = new Action<Session>() {
        @Override/*from  w  w w  .j a va 2 s .co  m*/
        public void run(Session session) {
            Department department1 = (Department) session.get(Department.class, 1L);
            employeeRef.set((Employee) session.get(Employee.class, 1L));
            department2Ref.set((Department) session.get(Department.class, 2L));
            ((LazinessManageable) department2Ref.get().getEmployees()).load();
            employeeRef.get().setDepartment(department1);
            Assert.assertEquals(1, department1.getEmployees().size());
            ((LazinessManageable) department1.getEmployees()).load();
        }
    };
    execute(handler);

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {
            Department department1 = (Department) session.get(Department.class, 1L);
            Department department2 = (Department) session.get(Department.class, 2L);
            Employee employee = (Employee) session.get(Employee.class, 1L);
            department2Ref.get().getEmployees().add(employeeRef.get());
            Assert.assertEquals(1, department1.getEmployees().size());
            Assert.assertEquals(0, department2.getEmployees().size());
            for (Employee e : department2Ref.get().getEmployees()) {
                Assert.assertFalse(session.contains(e));
            }
            Assert.assertSame(department1, employee.getDepartment());
            session.merge(department2Ref.get());
            Assert.assertEquals(department2, employee.getDepartment());
            Assert.assertEquals(0, department1.getEmployees().size());
            Assert.assertEquals(1, department2.getEmployees().size());
        }
    };
    execute(handler);
}

From source file:org.babyfish.test.hibernate.model.setandref.DbTest.java

License:Open Source License

private static void testMergeDepartment(final boolean loadBeforeMerge) {
    Object[] arr = load();/*  w w w.j  a  v  a2 s  . c  o  m*/
    Action<Session> handler;
    final Department detachedDepartment1 = (Department) arr[0];
    final Department detachedDepartment2 = (Department) arr[1];
    final Employee detachedEmployee = (Employee) arr[2];

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {

            session.setFlushMode(FlushMode.COMMIT);

            Department department1 = (Department) session.get(Department.class, 1L);
            Department department2 = (Department) session.get(Department.class, 2L);
            Employee employee = (Employee) session.get(Employee.class, 1L);

            detachedDepartment1.getEmployees().add(detachedEmployee);

            if (loadBeforeMerge) {
                assertCollection(department1.getEmployees());
                assertCollection(department2.getEmployees());
                assertReference(employee.getDepartment());
            }

            session.merge(detachedDepartment1);

            assertCollection(department1.getEmployees(), employee);
            assertCollection(department2.getEmployees());
            assertReference(employee.getDepartment(), department1);
        }
    };
    execute(handler);

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {

            session.setFlushMode(FlushMode.COMMIT);

            Department department1 = (Department) session.get(Department.class, 1L);
            Department department2 = (Department) session.get(Department.class, 2L);
            Employee employee = (Employee) session.get(Employee.class, 1L);

            detachedDepartment2.getEmployees().add(detachedEmployee);

            if (loadBeforeMerge) {
                assertCollection(department1.getEmployees(), employee);
                assertCollection(department2.getEmployees());
                assertReference(employee.getDepartment(), department1);
            }

            session.merge(detachedDepartment2);

            assertCollection(department1.getEmployees());
            assertCollection(department2.getEmployees(), employee);
            assertReference(employee.getDepartment(), department2);
        }
    };
    execute(handler);

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {

            session.setFlushMode(FlushMode.COMMIT);

            Department department1 = (Department) session.get(Department.class, 1L);
            Department department2 = (Department) session.get(Department.class, 2L);
            Employee employee = (Employee) session.get(Employee.class, 1L);

            detachedDepartment2.getEmployees().clear();

            if (loadBeforeMerge) {
                assertCollection(department1.getEmployees());
                assertCollection(department2.getEmployees(), employee);
                assertReference(employee.getDepartment(), department2);
            }

            session.merge(detachedDepartment2);

            assertCollection(department1.getEmployees());
            assertCollection(department2.getEmployees());
            assertReference(employee.getDepartment());
        }
    };
    execute(handler);
}

From source file:org.babyfish.test.hibernate.model.setandset.DbTest.java

License:Open Source License

private void testMergeStudent(final boolean loadBeforeMerge) {
    Object[] arr = load();//  ww w. j a v a  2 s.  c  o  m
    final Student detachedStudent1 = (Student) arr[0];
    final Student detachedStudent2 = (Student) arr[1];
    final Course detachedCourse1 = (Course) arr[2];
    final Course detachedCourse2 = (Course) arr[3];

    Action<Session> handler;

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {
            session.setFlushMode(FlushMode.COMMIT);

            Student student1 = (Student) session.get(Student.class, 1L);
            Student student2 = (Student) session.get(Student.class, 2L);
            Course course1 = (Course) session.get(Course.class, 1L);
            Course course2 = (Course) session.get(Course.class, 2L);
            detachedStudent1.getCourses().add(detachedCourse1);

            if (loadBeforeMerge) {
                assertCollection(student1.getCourses());
                assertCollection(student2.getCourses());
                assertCollection(course1.getStudents());
                assertCollection(course2.getStudents());
            }

            session.merge(detachedStudent1);

            assertCollection(student1.getCourses(), course1);
            assertCollection(student2.getCourses());
            assertCollection(course1.getStudents(), student1);
            assertCollection(course2.getStudents());
        }
    };
    execute(handler);

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {
            session.setFlushMode(FlushMode.COMMIT);

            Student student1 = (Student) session.get(Student.class, 1L);
            Student student2 = (Student) session.get(Student.class, 2L);
            Course course1 = (Course) session.get(Course.class, 1L);
            Course course2 = (Course) session.get(Course.class, 2L);
            detachedStudent1.getCourses().add(detachedCourse2);

            if (loadBeforeMerge) {
                assertCollection(student1.getCourses(), course1);
                assertCollection(student2.getCourses());
                assertCollection(course1.getStudents(), student1);
                assertCollection(course2.getStudents());
            }

            session.merge(detachedStudent1);

            assertCollection(student1.getCourses(), course1, course2);
            assertCollection(student2.getCourses());
            assertCollection(course1.getStudents(), student1);
            assertCollection(course2.getStudents(), student1);
        }
    };
    execute(handler);

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {
            session.setFlushMode(FlushMode.COMMIT);

            Student student1 = (Student) session.get(Student.class, 1L);
            Student student2 = (Student) session.get(Student.class, 2L);
            Course course1 = (Course) session.get(Course.class, 1L);
            Course course2 = (Course) session.get(Course.class, 2L);
            detachedStudent2.getCourses().add(detachedCourse1);

            if (loadBeforeMerge) {
                assertCollection(student1.getCourses(), course1, course2);
                assertCollection(student2.getCourses());
                assertCollection(course1.getStudents(), student1);
                assertCollection(course2.getStudents(), student1);
            }

            session.merge(detachedStudent2);

            assertCollection(student1.getCourses(), course1, course2);
            assertCollection(student2.getCourses(), course1);
            assertCollection(course1.getStudents(), student1, student2);
            assertCollection(course2.getStudents(), student1);
        }
    };
    execute(handler);

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {
            session.setFlushMode(FlushMode.COMMIT);

            Student student1 = (Student) session.get(Student.class, 1L);
            Student student2 = (Student) session.get(Student.class, 2L);
            Course course1 = (Course) session.get(Course.class, 1L);
            Course course2 = (Course) session.get(Course.class, 2L);
            detachedStudent2.getCourses().add(detachedCourse2);

            if (loadBeforeMerge) {
                assertCollection(student1.getCourses(), course1, course2);
                assertCollection(student2.getCourses(), course1);
                assertCollection(course1.getStudents(), student1, student2);
                assertCollection(course2.getStudents(), student1);
            }

            session.merge(detachedStudent2);

            assertCollection(student1.getCourses(), course1, course2);
            assertCollection(student2.getCourses(), course1, course2);
            assertCollection(course1.getStudents(), student1, student2);
            assertCollection(course2.getStudents(), student1, student2);
        }
    };
    execute(handler);

    handler = new Action<Session>() {
        @Override
        public void run(Session session) {
            session.setFlushMode(FlushMode.COMMIT);

            Student student1 = (Student) session.get(Student.class, 1L);
            Student student2 = (Student) session.get(Student.class, 2L);
            Course course1 = (Course) session.get(Course.class, 1L);
            Course course2 = (Course) session.get(Course.class, 2L);
            detachedStudent1.getCourses().remove(detachedCourse1);

            if (loadBeforeMerge) {
                assertCollection(student1.getCourses(), course1, course2);
                assertCollection(student2.getCourses(), course1, course2);
                assertCollection(course1.getStudents(), student1, student2);
                assertCollection(course2.getStudents(), student1, student2);
            }

            session.merge(detachedStudent1);

            assertCollection(student1.getCourses(), course2);
            assertCollection(student2.getCourses(), course1, course2);
            assertCollection(course1.getStudents(), student2);
            assertCollection(course2.getStudents(), student1, student2);
        }
    };
    execute(handler);
}