Example #1
0
  private void createData() {
    Session s = openSession();
    s.getTransaction().begin();
    Calendar cal = Calendar.getInstance();
    cal.set(2006, 10, 11);
    Driver driver = new Driver();
    driver.setDelivery(cal.getTime());
    driver.setId(1);
    driver.setName("Emmanuel");
    driver.setScore(5);
    driver.setTeacher("andre");
    s.persist(driver);

    cal.set(2007, 10, 11);
    driver = new Driver();
    driver.setDelivery(cal.getTime());
    driver.setId(2);
    driver.setName("Gavin");
    driver.setScore(3);
    driver.setTeacher("aaron");
    s.persist(driver);

    cal.set(2004, 10, 11);
    driver = new Driver();
    driver.setDelivery(cal.getTime());
    driver.setId(3);
    driver.setName("Liz");
    driver.setScore(5);
    driver.setTeacher("max");
    s.persist(driver);
    s.getTransaction().commit();
    s.close();
  }
Example #2
0
  /**
   * Creates the ResourceAllocationSettingData for all the types (as shown in the table below) by
   * calling each method dedicated to the creation of a specific RASD.
   *
   * <p>Each of thes method should have the format: <br>
   * <code> createRASD[idResource] </code> <br>
   * E.g The method for idResource 10 will be createRASD10
   *
   * <p>Implement methods as needed and follow examples
   *
   * <pre>
   * +------------+-------------------------+
   * | idResource | name                    |
   * +------------+-------------------------+
   * |          1 | Other                   |
   * |          2 | Computer_System         |
   * |          3 | Processor               |
   * |          4 | Memory                  |
   * |          5 | IDE_Controller          |
   * |          6 | Parallel_SCSI_HBA       |
   * |          7 | FC_HBA                  |
   * |          8 | iSCSI_HBA               |
   * |          9 | IB_HCA                  |
   * |         10 | Ethernet_Adapter        |
   * |         11 | Other_Network_Adapter   |
   * |         12 | IO_Slot                 |
   * |         13 | IO_Device               |
   * |         14 | Floppy_Drive            |
   * |         15 | CD_Drive                |
   * |         16 | DVD_drive               |
   * |         17 | Disk_Drive              |
   * |         18 | Tape_Drive              |
   * |         19 | Storage_Extent          |
   * |         20 | Other_storage_device    |
   * |         21 | Serial_port             |
   * |         22 | Parallel_port           |
   * |         23 | USB_Controller          |
   * |         24 | Graphics_controller     |
   * |         25 | IEEE_1394_Controller    |
   * |         26 | Partitionable_Unit      |
   * |         27 | Base_Partitionable_Unit |
   * |         28 | Power                   |
   * |         29 | Cooling_Capacity        |
   * |         30 | Ethernet_Switch_Port    |
   * |         31 | DMTF_reserved           |
   * |         32 | Vendor_Reserved         |
   * +------------+-------------------------+
   * </pre>
   */
  public void createResourceAllocationSettingData() {
    Session session = null;
    Transaction transaction = null;

    try {

      session = HibernateUtil.getSession();
      session.beginTransaction();

      // Create the Rasds
      createRASD10(session);

      // This array of integers contains a list of resource types in which a rasd_management
      // entry will be made for each one and all related to the current virtualappliance
      int[] resourceTypes = {10};

      transaction = session.getTransaction();

      transaction.commit();
    } catch (Exception e) {
      e.printStackTrace();

      transaction = session.getTransaction();

      if (transaction != null && transaction.isActive()) {
        transaction.rollback();
      }
    }
  }
Example #3
0
  public static Object readRecordByCode(String code, int objectType) {
    // TODO by the candidate
    /*
     * This method is called when you select record in list view of any
     * entity and also called after you save a record to re-bind the record
     * again the code parameter is the first column of the row you have
     * selected and the type is identifier of the object type and may be
     * TYPE_PRODUCT , TYPE_CUSTOMER or TYPE_SALESORDER
     */

    Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();

    Object o = null;
    try {
      switch (objectType) {
        case TYPE_CUSTOMER:
          o = session.get(Customer.class, code);
          break;
        case TYPE_PRODUCT:
          o = session.get(Product.class, code);
          break;
        case TYPE_SALESORDER:
          o = session.get(SalesOrder.class, code);
          break;
        default:
          break;
      }
      session.getTransaction().commit();
    } catch (HibernateException e) {
      logger.error("Error While Retrieving", e);
      session.getTransaction().rollback();
    }
    return o;
  }
  @Path("{id}")
  @PUT
  @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Collaborateur modifierCollaborateur(Collaborateur collaborateur) {

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();

    try {
      session.beginTransaction();
      String mdp =
          (String)
              session
                  .createQuery(
                      "select col.motDePasse from Collaborateur col WHERE col = :collaborateur")
                  .setEntity("collaborateur", collaborateur)
                  .uniqueResult();

      if (!collaborateur.getMotDePasse().equals(mdp))
        collaborateur.setMotDePasse(
            Security.get_SHA_1_SecurePassword(collaborateur.getMotDePasse()));

      session.update(collaborateur);

      session.getTransaction().commit();
    } catch (Exception e) {
      if (session.getTransaction() != null) session.getTransaction().rollback();
    } finally {
      if (session.isOpen()) {
        session.close();
      }
    }

    return collaborateur;
  }
  @Test
  public void testTempTableGenerationIsolation() throws Throwable {
    Session s = openSession();
    s.beginTransaction();

    Truck truck = new Truck();
    truck.setVin("123t");
    truck.setOwner("Steve");
    s.save(truck);

    // manually flush the session to ensure the insert happens
    s.flush();

    // now issue a bulk delete against Car which should force the temp table to be
    // created.  we need to test to ensure that this does not cause the transaction
    // to be committed...
    s.createQuery("delete from Vehicle").executeUpdate();

    s.getTransaction().rollback();
    s.close();

    s = openSession();
    s.beginTransaction();
    List list = s.createQuery("from Car").list();
    assertEquals("temp table gen caused premature commit", 0, list.size());
    s.createQuery("delete from Car").executeUpdate();
    s.getTransaction().rollback();
    s.close();
  }
  /**
   * Returns a <code>List&lt;String&gt;</code> of distinct MGI references suitable for autocomplete
   * sourcing.
   *
   * @return a <code>List&lt;String&gt;</code> of distinct MGI references suitable for autocomplete
   *     sourcing.
   */
  public List<String> getMGIReferences() {
    List<String> targetList = new ArrayList();
    Session session = factory.getCurrentSession();
    List sourceList = null;
    try {
      session.beginTransaction();
      sourceList =
          session
              .createSQLQuery(
                  "SELECT DISTINCT mgi_ref FROM genes ORDER BY CAST(mgi_ref AS unsigned) ASC")
              .list();
      session.getTransaction().commit();
    } catch (HibernateException e) {
      session.getTransaction().rollback();
      throw e;
    }

    if (sourceList != null) {
      Iterator iterator = sourceList.iterator();
      while (iterator.hasNext()) {
        String mgiRef = (String) iterator.next();
        targetList.add(Utils.wrap(mgiRef, "\""));
      }
    }

    return targetList;
  }
  @Test
  public void testUpdateAfterClear() {
    Session s = openSession();
    s.beginTransaction();
    Parent p = new Parent("p");
    s.save(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    p = (Parent) s.load(Parent.class, "p");
    // clear...
    s.clear();
    // now try to reattach...
    s.update(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    s.delete(p);
    s.getTransaction().commit();
    s.close();
  }
  @Test
  public void testBasicOps() {
    Session session = openSession();
    session.beginTransaction();
    Country country = new Country("US", "United States of America");
    session.persist(country);
    Person person = new Person("Steve", new Address());
    person.getAddress().setLine1("123 Main");
    person.getAddress().setCity("Anywhere");
    person.getAddress().setCountry(country);
    person.getAddress().setPostalCode("123456789");
    session.persist(person);
    session.getTransaction().commit();
    session.close();

    session = openSession();
    session.beginTransaction();
    session.createQuery("from Person p where p.address.country.iso2 = 'US'").list();
    // same query!
    session.createQuery("from Person p where p.address.country.id = 'US'").list();
    person = (Person) session.load(Person.class, person.getId());
    session.delete(person);
    List countries = session.createQuery("from Country").list();
    assertEquals(1, countries.size());
    session.delete(countries.get(0));

    session.getTransaction().commit();
    session.close();
  }
  @Test
  public void testMultiLoadClearsBatchFetchQueue() {
    final EntityKey entityKey =
        new EntityKey(1, sessionFactory().getEntityPersister(SimpleEntity.class.getName()));

    Session session = openSession();
    session.getTransaction().begin();
    // create a proxy, which should add an entry to the BatchFetchQueue
    SimpleEntity first = session.byId(SimpleEntity.class).getReference(1);
    assertTrue(
        ((SessionImplementor) session)
            .getPersistenceContext()
            .getBatchFetchQueue()
            .containsEntityKey(entityKey));

    // now bulk load, which should clean up the BatchFetchQueue entry
    List<SimpleEntity> list =
        session.byMultipleIds(SimpleEntity.class).enableSessionCheck(true).multiLoad(ids(56));

    assertEquals(56, list.size());
    assertFalse(
        ((SessionImplementor) session)
            .getPersistenceContext()
            .getBatchFetchQueue()
            .containsEntityKey(entityKey));

    session.getTransaction().commit();
    session.close();
  }
Example #10
0
  public static List<FacetedQueries> getFacetedQueriesByInternalStaffId(int internalStaffId) {
    List<FacetedQueries> facetedQueries = null;
    Session session = null;
    try {

      session = sessionFactory.openSession();
      session.beginTransaction();
      facetedQueries =
          (List<FacetedQueries>)
              session
                  .createQuery(
                      "from FacetedQueries fq where fq.internalAuthor.internalId= :internalStaffId")
                  .setParameter("internalStaffId", internalStaffId)
                  .list();
      session.getTransaction().commit();

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      if (session != null) {
        session.getTransaction().rollback();
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }

    return facetedQueries;
  }
Example #11
0
  public static FacetedQueries getFacetedQueriesById(int facetQueryId) {
    FacetedQueries facetedQueries = null;
    Session session = null;
    try {

      session = sessionFactory.openSession();
      session.beginTransaction();
      facetedQueries =
          (FacetedQueries)
              session
                  .createQuery("from FacetedQueries fq where fq.facetedQueryId = :facetQueryId")
                  .setParameter("facetQueryId", facetQueryId)
                  .uniqueResult();
      session.getTransaction().commit();

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      if (session != null) {
        session.getTransaction().rollback();
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }

    return facetedQueries;
  }
Example #12
0
  /* Method to CREATE FacetedQuery in the database */
  public static Integer createFacetedQueries(FacetedQueries facetedQuery) {

    Session session = null;
    Integer facetedQueryId = null;

    try {

      session = sessionFactory.openSession();
      session.beginTransaction();

      facetedQueryId = (Integer) session.save(facetedQuery);

      session.getTransaction().commit();

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      System.out.println(ex.getStackTrace());
      if (session != null) {
        session.getTransaction().rollback();
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }

    return facetedQueryId;
  }
  /**
   * Inserts more entries in the random numbers pool. Numbers are obtained from the QRBG service.
   * The total amount of integers inserted can be calculated as ({@link #NUMBER_OF_BYTES}/4 * {@link
   * #NUMBER_OF_REQUESTS}.
   *
   * @throws IOException If there is no Internet connectivity.
   * @throws ServiceDeniedException If the QRBG account is not valid.
   * @see <a href="http://random.irb.hr/">QRBG Service</a>
   * @since 1.0
   */
  private void insertMoreNumbersInPool() throws IOException, ServiceDeniedException {
    QRBG source = new QRBG(SettingBusiness.getQRBGUsername(), SettingBusiness.getQRBGPassword());
    for (int request = 0; request < NUMBER_OF_REQUESTS; request++) {
      byte[] buffer = new byte[NUMBER_OF_BYTES];
      source.getBytes(buffer, NUMBER_OF_BYTES);

      Session session = HibernateUtil.getSession();
      try {
        session.beginTransaction();
        for (int i = 0; i < (NUMBER_OF_BYTES - 4); i += 4) {
          double randomNumber = QRBG.readInt(buffer, i);
          if (randomNumber < 0) {
            randomNumber *= -1;
          }
          randomNumber /= Integer.MAX_VALUE;

          if (randomNumber != 0) {
            session.save(new RandomNumber(randomNumber));
          }
        }
        session.getTransaction().commit();
      } catch (HibernateException ex) {
        session.getTransaction().rollback();
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
      } finally {
        HibernateUtil.closeSession(session);
      }
    }
  }
  /**
   * Gets the given amount of random numbers from the random numbers pool. The effectiveness of this
   * method depends on a proper configuration of a valid account on the QRBG service and an active
   * Internet connection. Also, the QRBG service uses the port 1227. Make sure your firewall is
   * configured properly.
   *
   * @param amount the amount of random numbers to get.
   * @throws IOException If there is no Internet connectivity.
   * @throws ServiceDeniedException If the QRBG account is not valid.
   * @see <a href="http://random.irb.hr/">QRBG Service</a>
   * @see RandomNumber
   * @since 1.0
   */
  public List<Double> getRandomNumbers(int amount) throws IOException, ServiceDeniedException {
    List<RandomNumber> numbersList = getRandomNumbersFromPool(amount);

    if (numbersList.size() < amount) {
      insertMoreNumbersInPool();
      numbersList = getRandomNumbersFromPool(amount);
    }

    List<Double> returnList = new ArrayList<Double>();
    Session session = HibernateUtil.getSession();
    try {
      session.beginTransaction();
      for (int i = 0; i < amount; i++) {
        RandomNumber randomNumber = numbersList.get(i);
        returnList.add(randomNumber.getValue());
        session.delete(randomNumber);
      }
      session.getTransaction().commit();
    } catch (HibernateException ex) {
      session.getTransaction().rollback();
      Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      HibernateUtil.closeSession(session);
    }

    return returnList;
  }
 public void saveNotification(String institutionName, String status) {
   Session hibernate = null;
   try {
     hibernate = HibernateUtil.getSession();
     hibernate.beginTransaction();
     Notification notification = new Notification();
     notification.setEmail(ApplicationProperties.getProperty("email.admin"));
     notification.setSubject(
         String.format(
             ApplicationProperties.getProperty("email.admin.robot.subject"), institutionName));
     notification.setMessage(
         String.format(
                 ApplicationProperties.getProperty("email.admin.robot.body"),
                 institutionName,
                 status)
             + ApplicationProperties.getProperty("email.signature"));
     notification.setType(NotificationType.ROBOTCHECK);
     notification.setDate(new Date());
     hibernate.save(notification);
     hibernate.getTransaction().commit();
   } catch (Exception ex) {
     if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
       hibernate.getTransaction().rollback();
       logger.error("Failure", ex);
     }
   }
 }
  public void testLoadingStrategies() {
    Session s = openSession();
    s.beginTransaction();
    Customer cust = new Customer("Acme, Inc.");
    Order order = new Order(new Order.Id(cust, 1));
    cust.getOrders().add(order);
    s.save(cust);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();

    cust = (Customer) s.get(Customer.class, cust.getId());
    assertEquals(1, cust.getOrders().size());
    s.clear();

    cust = (Customer) s.createQuery("from Customer").uniqueResult();
    assertEquals(1, cust.getOrders().size());
    s.clear();

    cust = (Customer) s.createQuery("from Customer c join fetch c.orders").uniqueResult();
    assertEquals(1, cust.getOrders().size());
    s.clear();

    s.delete(cust);
    s.getTransaction().commit();
    s.close();
  }
Example #17
0
 @Test
 public void testAdd4() {
   Session session = null;
   try {
     session = HibernateUtil.openSession();
     session.beginTransaction();
     Classroom c = new Classroom();
     c.setGrade("2011");
     c.setName("计算机");
     // 此时classroom没有存,加了cascade="all" 会级联保存classroom
     Student stu1 = new Student();
     stu1.setClassroom(c);
     stu1.setName("3243432");
     session.save(stu1);
     Student stu2 = new Student();
     stu2.setClassroom(c);
     stu2.setName("2234434432");
     session.save(stu2);
     session.getTransaction().commit();
   } catch (Exception e) {
     e.printStackTrace();
     if (null != session) {
       session.getTransaction().rollback();
     }
   } finally {
     HibernateUtil.close(session);
   }
 }
  @Test
  public void testBasicExpectedBehavior() {
    Session session = getNewSession("jboss");
    session.beginTransaction();
    Customer steve = new Customer(1L, "steve");
    session.save(steve);
    session.getTransaction().commit();
    session.close();

    session = getNewSession("acme");
    try {
      session.beginTransaction();
      Customer check = (Customer) session.get(Customer.class, steve.getId());
      Assert.assertNull("tenancy not properly isolated", check);
    } finally {
      session.getTransaction().commit();
      session.close();
    }

    session = getNewSession("jboss");
    session.beginTransaction();
    session.delete(steve);
    session.getTransaction().commit();
    session.close();
  }
  @Test
  @SuppressWarnings({"unchecked"})
  public void testIterateWithEvictBottomOfLoop() {
    Session s = openSession();
    s.beginTransaction();
    Set parents = new HashSet();
    for (int i = 0; i < 5; i++) {
      Parent p = new Parent(String.valueOf(i + 100));
      Child child = new Child("child" + i);
      child.setParent(p);
      p.getChildren().add(child);
      s.save(p);
      parents.add(p);
    }
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    for (Iterator it = s.createQuery("from Parent").iterate(); it.hasNext(); ) {
      Parent p = (Parent) it.next();
      assertEquals(1, p.getChildren().size());
      s.evict(p);
    }
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    for (Object parent : parents) {
      s.delete(parent);
    }
    s.getTransaction().commit();
    s.close();
  }
  @Test
  public void testTableIdentifiers() {
    Session session = getNewSession("jboss");
    session.beginTransaction();
    Invoice orderJboss = new Invoice();
    session.save(orderJboss);
    Assert.assertEquals(Long.valueOf(1), orderJboss.getId());
    session.getTransaction().commit();
    session.close();

    session = getNewSession("acme");
    session.beginTransaction();
    Invoice orderAcme = new Invoice();
    session.save(orderAcme);
    Assert.assertEquals(Long.valueOf(1), orderAcme.getId());
    session.getTransaction().commit();
    session.close();

    session = getNewSession("jboss");
    session.beginTransaction();
    session.delete(orderJboss);
    session.getTransaction().commit();
    session.close();

    session = getNewSession("acme");
    session.beginTransaction();
    session.delete(orderAcme);
    session.getTransaction().commit();
    session.close();

    sessionFactory.getStatisticsImplementor().clear();
  }
  @SuppressWarnings("unchecked")
  @Path("/managerrh/{id}")
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public List<Collaborateur> getCollaborateurByManagerRh(@PathParam("id") int id) {

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    List<Collaborateur> collaborateurs = null;

    try {
      session.beginTransaction();
      ManagerRh managerRh = (ManagerRh) session.get(ManagerRh.class, new Long(id));

      if (managerRh != null) {
        collaborateurs =
            session
                .createQuery(
                    " select col from Collaborateur col, ManagerRh man"
                        + " where man = :managerrh AND col IN elements(man.collaborateurs)")
                .setEntity("managerRh", managerRh)
                .list();
      }

      session.getTransaction().commit();
    } catch (Exception e) {
      if (session.getTransaction() != null) session.getTransaction().rollback();
    } finally {
      if (session.isOpen()) {
        session.close();
      }
    }

    return collaborateurs;
  }
  @Create
  @Transactional
  public void initialize() {

    LOGGER.debug("hibernateSession.isConnected(): " + hibernateSession.isConnected());
    LOGGER.debug("hibernateSession.isOpen(): " + hibernateSession.isOpen());
    LOGGER.debug("hibernateSession.getTransaction(): " + hibernateSession.getTransaction());
    LOGGER.debug(
        "hibernateSession.getTransaction().isActive(): "
            + hibernateSession.getTransaction().isActive());

    localeId = charmsUser.getLocaleId();
    themeId = charmsUser.getThemeId();
    timezoneId = charmsUser.getTimezoneId();

    email = charmsUser.getEmail();

    LOGGER.debug(
        "initialized userPropertiesActionBean: "
            + " "
            + localeId
            + " "
            + themeId
            + " "
            + timezoneId);
  }
  @SuppressWarnings("unchecked")
  @Path("/encadrant/{id}")
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public List<Collaborateur> getCollaborateurByEncadrant(@PathParam("id") int id) {

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    List<Collaborateur> collaborateurs = null;

    try {
      session.beginTransaction();
      Encadrant encadrant = (Encadrant) session.get(Encadrant.class, new Long(id));

      if (encadrant != null) {
        collaborateurs =
            session
                .createQuery(
                    "select distinct col from Collaborateur as col join col.fichesEvaluations as fiche"
                        + " join fiche.evaluations as eval where eval.encadrant = :encadrant")
                .setEntity("encadrant", encadrant)
                .list();
      }
      session.getTransaction().commit();
    } catch (Exception e) {
      if (session.getTransaction() != null) session.getTransaction().rollback();
    } finally {
      if (session.isOpen()) {
        session.close();
      }
    }

    return collaborateurs;
  }
 public List<Semester> SemesterSearch(String search) {
   Session session = HibernateUtil.getSessionFactory().getCurrentSession();
   if (!session.getTransaction().isActive()) {
     session.beginTransaction();
   }
   List<Semester> lstSemesters = null;
   try {
     StringBuilder buider = new StringBuilder();
     buider.append("FROM Semester se ");
     buider.append("WHERE se.name LIKE :sn ");
     buider.append("OR se.curriculum.branch.name LIKE :sn ");
     buider.append("OR se.curriculum.name LIKE :sn ");
     buider.append("OR se.user.fullName LIKE :sn");
     Query query = session.createQuery(buider.toString());
     query.setParameter("sn", "%" + search + "%");
     lstSemesters = (List<Semester>) query.list();
     for (Semester semester : lstSemesters) {
       semester.getId();
       semester.getCurriculum().getBranch().getName();
       semester.getCurriculum().getName();
       semester.getUser().getFullName();
     }
   } catch (HibernateException ex) {
     ex.printStackTrace();
     session.getTransaction().rollback();
   }
   session.getTransaction().commit();
   return lstSemesters;
 }
  @Test
  public void testCreateAndDelete() {
    Date now = new Date();

    Session s = openSession();

    s.doWork(new ValidateSomeEntityColumns((SessionImplementor) s));
    s.doWork(new ValidateRowCount((SessionImplementor) s, SOME_ENTITY_TABLE_NAME, 0));
    s.doWork(new ValidateRowCount((SessionImplementor) s, SOME_OTHER_ENTITY_TABLE_NAME, 0));

    s.beginTransaction();
    SomeEntity someEntity = new SomeEntity(now);
    SomeOtherEntity someOtherEntity = new SomeOtherEntity(1);
    s.save(someEntity);
    s.save(someOtherEntity);
    s.getTransaction().commit();
    s.close();

    s = openSession();

    s.doWork(new ValidateRowCount((SessionImplementor) s, SOME_ENTITY_TABLE_NAME, 1));
    s.doWork(new ValidateRowCount((SessionImplementor) s, SOME_OTHER_ENTITY_TABLE_NAME, 1));

    s.beginTransaction();
    s.delete(someEntity);
    s.delete(someOtherEntity);
    s.getTransaction().commit();

    s.doWork(new ValidateRowCount((SessionImplementor) s, SOME_ENTITY_TABLE_NAME, 0));
    s.doWork(new ValidateRowCount((SessionImplementor) s, SOME_OTHER_ENTITY_TABLE_NAME, 0));

    s.close();
  }
 /**
  * method used to get list of all semesters
  *
  * @param int curriculumId
  * @param boolean planned
  * @return List<Semester>
  */
 public List<Semester> getSemesters(int studentClassId, boolean planned) {
   Session session = HibernateUtil.getSessionFactory().getCurrentSession();
   if (!session.getTransaction().isActive()) {
     session.beginTransaction();
   }
   List<Semester> lstSemesters = null;
   try {
     StringBuilder strBld = new StringBuilder();
     strBld.append("SELECT sm FROM StudentClass st ");
     strBld.append("INNER JOIN st.curriculum c ");
     strBld.append("INNER JOIN c.semesters sm ");
     strBld.append("LEFT JOIN sm.semesterSchedules ss ");
     strBld.append("WHERE st.id = :i ");
     if (planned) {
       strBld.append("AND ss.semester != null");
     } else {
       strBld.append("AND ss.semester = null");
     }
     Query query = session.createQuery(strBld.toString());
     query.setParameter("i", studentClassId);
     lstSemesters = (List<Semester>) query.list();
     for (Semester semester : lstSemesters) {
       semester.getId();
       semester.getName();
     }
   } catch (HibernateException ex) {
     ex.printStackTrace();
     session.getTransaction().rollback();
   }
   session.getTransaction().commit();
   return lstSemesters;
 }
  public void testUpdateOwnerAfterEvict() {
    Session s = openSession();
    s.beginTransaction();
    Parent p = new Parent("p");
    p.getChildren().add(new Child("c"));
    s.save(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    p = (Parent) s.get(Parent.class, "p");
    // evict...
    s.evict(p);
    // now try to reattach...
    s.update(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    s.delete(p);
    s.getTransaction().commit();
    s.close();
  }
Example #28
0
  /* (non-Javadoc)
   * @see com.adibrata.smartdealer.service.othertransactions.OtherReceive#Save(com.adibrata.smartdealer.model.OtherRcvHdr, com.adibrata.smartdealer.model.OtherRcvDtl)
   */
  @SuppressWarnings("unused")
  @Override
  public void Save(String usrupd, OtherRcvHdr otherRcvHdr, List<OtherRcvDtl> lstotherRcvDtl)
      throws Exception {
    // TODO Auto-generated method stub
    session.getTransaction().begin();
    try {
      String transno =
          TransactionNo(
              session,
              TransactionType.otherreceive,
              otherRcvHdr.getPartner().getPartnerCode(),
              otherRcvHdr.getOffice().getId());
      otherRcvHdr.setOtherRcvNo(transno);
      otherRcvHdr.setDtmCrt(dtmupd.getTime());
      otherRcvHdr.setDtmUpd(dtmupd.getTime());
      session.save(otherRcvHdr);

      for (OtherRcvDtl arow : lstotherRcvDtl) {
        OtherRcvDtl otherRcvDtl = new OtherRcvDtl();
        otherRcvDtl.setOtherRcvHdr(otherRcvHdr);
        otherRcvDtl.setDtmCrt(dtmupd.getTime());
        otherRcvDtl.setDtmUpd(dtmupd.getTime());
        session.save(otherRcvDtl);
      }
      session.getTransaction().commit();

    } catch (Exception exp) {
      session.getTransaction().rollback();
      ExceptionEntities lEntExp = new ExceptionEntities();
      lEntExp.setJavaClass(Thread.currentThread().getStackTrace()[1].getClassName());
      lEntExp.setMethodName(Thread.currentThread().getStackTrace()[1].getMethodName());
      ExceptionHelper.WriteException(lEntExp, exp);
    }
  }
Example #29
0
 @SuppressWarnings("unchecked")
 public static List<Object> listCurrentRecords(int objectType) {
   // TODO by the candidate
   /*
    * This method is called when you open any list screen and should return
    * all records of the specified type
    */
   Session session = sessionFactory.getCurrentSession();
   List<Object> objList = new ArrayList<Object>();
   try {
     session.beginTransaction();
     switch (objectType) {
       case TYPE_CUSTOMER:
         objList = session.createCriteria(Customer.class).list();
         break;
       case TYPE_PRODUCT:
         objList = session.createCriteria(Product.class).list();
         break;
       case TYPE_SALESORDER:
         Set<SalesOrder> set =
             new HashSet<SalesOrder>(session.createCriteria(SalesOrder.class).list());
         objList = new ArrayList<Object>(set);
         break;
       default:
         break;
     }
     session.getTransaction().commit();
   } catch (HibernateException e) {
     logger.error("Error while retrieving records", e);
     session.getTransaction().rollback();
   }
   return objList;
 }
Example #30
0
 private void deleteData() {
   Session s = openSession();
   s.getTransaction().begin();
   s.createQuery("delete " + Driver.class.getName() + " t").executeUpdate();
   s.getTransaction().commit();
   s.close();
 }