示例#1
0
  @SuppressWarnings("unchecked")
  public static java.util.List<Object> getListData(
      Class<?> classBean, String strKey1, Object value1, String strKey2, Object value2) {
    java.util.List<Object> result = new java.util.ArrayList<Object>();
    Session session = null;
    try {
      session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();

      Criteria criteria = session.createCriteria(classBean);
      if (strKey1 != null) {
        criteria.add(Restrictions.like(strKey1, value1));
      }
      if (strKey2 != null) {
        criteria.add(Restrictions.like(strKey2, value2));
      }

      result = criteria.list();

      tx.commit();

    } finally {
      if (session != null) {
        session.close();
      }
    }
    return result;
  }
  /**
   * Updates given object in the database. Returns true if update is successful, otherwise returns
   * false.
   *
   * @param object
   * @return
   */
  public synchronized boolean update(Object object) {

    Transaction transaction = null;
    Session session = null;
    boolean errorResult = false;

    try {
      session = HibernateUtil.getCurrentSession();
      transaction = session.beginTransaction();
      session.update(object);
      transaction.commit();

      return true;
    } catch (HibernateException exception) {
      rollback(transaction);
      BookingLogger.getDefault()
          .severe(this, Messages.METHOD_UPDATE, Messages.HIBERNATE_FAILED, exception);
      return errorResult;
    } catch (RuntimeException exception) {
      rollback(transaction);
      BookingLogger.getDefault()
          .severe(this, Messages.METHOD_UPDATE, Messages.GENERIC_FAILED, exception);
      return errorResult;
    } finally {
      closeSession();
    }
  }
示例#3
0
 @Override
 public void createProfessors(List<Professor> professorList) throws Exception {
   if (professorList == null) {
     throw new NullPointerException("Professors list is null");
   }
   if (professorList.size() < 1) {
     throw new IllegalArgumentException("Professors list is empty");
   }
   Session session = sessionFactory.openSession();
   Transaction transaction = session.getTransaction();
   transaction.begin();
   for (Professor professor : professorList) {
     try {
       session.save(professor);
     } catch (ConstraintViolationException e) {
       transaction.rollback();
       session.close();
       e.printStackTrace();
       throw new Exception(
           "Login or Email already exists (login = "******"; email = "
               + professor.getUser().getEmail()
               + ")");
     }
   }
   transaction.commit();
   session.close();
 }
示例#4
0
  public void commitTransaction(IObjectScope scope, ICmdbTransaction cmdbTx) {
    idCache.clear();
    aliasCache.clear();

    Session session = null;
    Transaction tx = null;
    Profiler.start("commitTx()");
    try {
      session = getSession(cmdbTx.getSession());
      tx = session.beginTransaction();
      for (ICi item : scope.getDestroyedICis()) {
        session.delete(item);
      }
      for (ICi item : scope.getNewICis()) {
        session.save(item);
      }
      for (ICi item : scope.getModifiedICis()) {
        session.update(item);
      }
      cmdbTx.setEndTs(new Date());
      storeTx(session, cmdbTx); // session.update(cmdbTx);
      tx.commit();

    } catch (HibernateException he) {
      if (tx != null) {
        tx.rollback();
      }
      throw he;
    } finally {
      closeSession(session);

      Profiler.stop("commitTx()");
    }
  }
 // 此方法用于动态条件查询
 public Collection find(Product product) throws ManagerProductException {
   Session session = null;
   Transaction tran = null;
   Collection list = null;
   try {
     session = HibernateUtils.getSession();
     tran = session.beginTransaction();
     Criteria crit = session.createCriteria(Product.class);
     if (product.getAuthor().equals("")) {
       crit.add(Restrictions.like("author", "%"));
     } else {
       crit.add(Restrictions.like("author", "%" + product.getAuthor() + "%"));
     }
     if (product.getName().equals("")) {
       crit.add(Restrictions.like("name", "%"));
     } else {
       crit.add(Restrictions.like("name", "%" + product.getName() + "%"));
     }
     if (product.getPublish().equals("")) {
       crit.add(Restrictions.like("publish", "%"));
     } else {
       crit.add(Restrictions.like("publish", "%" + product.getPublish() + "%"));
     }
     list = crit.list();
     tran.commit();
   } catch (Exception e) {
     e.printStackTrace();
     tran.rollback();
   } finally {
     session.close();
     return list;
   }
 }
  public ArrayList<StaffEntity> getAllStaff() {

    Session session = SessionFactoryProvider.getSessionFactory().openSession();

    ArrayList<StaffEntity> departmentStaff = new ArrayList<StaffEntity>();
    Transaction dbTransaction = null;

    try {
      dbTransaction = session.beginTransaction();
      List staffInDB = session.createQuery("FROM StaffEntity ").list();

      for (Iterator iterator = staffInDB.iterator(); iterator.hasNext(); ) {

        StaffEntity staff = (StaffEntity) iterator.next();
        departmentStaff.add(staff);
      }

      dbTransaction.commit();

    } catch (HibernateException error) {
      if (dbTransaction != null) dbTransaction.rollback();
      error.printStackTrace();
    } finally {
      session.close();
    }

    log.info("Number of staff on the department: " + departmentStaff.size());

    return departmentStaff;
  }
示例#7
0
 public <T> T execute(final ThrowingHibernateAction<T> action) throws Exception {
   synchronized (this) {
     Session session = null;
     Transaction transaction = null;
     try {
       session = (Session) getConnectionProvider().getConnection();
       transaction = session.beginTransaction();
       final T result = action.call(session);
       session.flush();
       transaction.commit();
       return result;
     } catch (ConnectionProviderException cpe) {
       if (transaction != null) {
         transaction.rollback();
       }
       throw new RuntimeException(cpe);
     } catch (Exception e) {
       if (transaction != null) {
         transaction.rollback();
       }
       throw e;
     } finally {
       getConnectionProvider().returnConnection(session);
     }
   }
 }
示例#8
0
 @Override
 public Member memberLogin(String login, String password) throws Exception {
   Session session = HibernateUtil.getSession();
   Transaction tx = null;
   Member member = null;
   try {
     String hql = "SELECT a FROM Member AS a WHERE a.login=:login AND a.password=:password";
     Query query = session.createQuery(hql);
     query.setString("login", login.trim());
     query.setString("password", password.trim());
     query.setMaxResults(1);
     tx = session.beginTransaction();
     member = (Member) query.uniqueResult();
     if (member != null && ("y").equals(member.getActivated().toLowerCase())) {
       member.setLoginTimes(Integer.valueOf(member.getLoginTimes() + 1));
       member.setLastLogin(new Date());
       session.update(member);
     }
     tx.commit();
   } catch (Exception ex) {
     if (tx != null) tx.rollback();
     logger.info("In class MemberServiceImpl:memberLogin()\n");
     ex.printStackTrace();
   } finally {
     HibernateUtil.closeSession();
   }
   return member;
 }
  /** @param dairy */
  private void populateBaseCollectionSessions(Dairy dairy) {
    CollectionSession cSession;

    Session session;
    Transaction transaction;

    session = getOrCreateSession();
    transaction = session.beginTransaction();

    dairy = (Dairy) session.load("Dairy", dairy.getCompanyId());

    cSession = DairyFactory.eINSTANCE.createCollectionSession();
    cSession.setCode("AM");
    cSession.setTimeOfDay(new Date(0, 0, 0, 6, 0));
    cSession.setDescription("The first collection session of the day");
    dairy.getCollectionSessions().add(cSession);

    cSession = DairyFactory.eINSTANCE.createCollectionSession();
    cSession.setCode("PM");
    cSession.setDescription("An additional collection session.");
    cSession.setTimeOfDay(new Date(0, 0, 0, 13, 0));
    dairy.getCollectionSessions().add(cSession);

    transaction.commit();
  }
示例#10
0
 public void save(Treatment treatment) {
   Session session = this.sessionFactory.openSession();
   Transaction tx = session.beginTransaction();
   session.persist(treatment);
   tx.commit();
   session.close();
 }
示例#11
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();
      }
    }
  }
示例#12
0
  @Override
  public List<Role> getAllRoles() {

    Session session = SessionFactoryProvider.getSessionFactory().openSession();
    Transaction tx = null;
    List<Role> allRoles = new ArrayList<Role>();

    try {
      tx = session.beginTransaction();
      Criteria criteria = session.createCriteria(Role.class);
      List<Role> roles = criteria.list();

      for (Role r : roles) {
        allRoles.add(r);
      }

      tx.commit();
    } catch (HibernateException e) {
      if (tx != null) {
        e.printStackTrace();
      }
    } finally {
      session.close();
    }

    return allRoles;
  }
示例#13
0
  public void save() {
    iProgress.setStatus("Saving solution ...");
    org.hibernate.Session hibSession = new ExamDAO().getSession();
    hibSession.setCacheMode(CacheMode.IGNORE);
    Transaction tx = null;
    try {
      tx = hibSession.beginTransaction();
      saveSolution(hibSession);
      tx.commit();

      iProgress.setPhase("Refreshing solution ...", 1);
      try {
        if (SolverServerImplementation.getInstance() != null)
          SolverServerImplementation.getInstance().refreshExamSolution(iSessionId, iExamTypeId);
        iProgress.incProgress();
      } catch (Exception e) {
        iProgress.warn("Unable to refresh solution, reason:" + e.getMessage(), e);
      }
    } catch (Exception e) {
      if (tx != null) tx.rollback();
      iProgress.fatal("Unable to save a solution, reason: " + e.getMessage(), e);
    } finally {
      // here we need to close the session since this code may run in a separate thread
      if (hibSession != null && hibSession.isOpen()) hibSession.close();
    }
  }
 @Override
 public Response updateRecords(
     int[] rowNumbers, ArrayList oldPersistentObjects, ArrayList persistentObjects)
     throws Exception {
   Response r = super.updateRecords(rowNumbers, oldPersistentObjects, persistentObjects);
   for (Object e : persistentObjects) {
     DireccionPersona d = (DireccionPersona) e;
     if (d.getTipoDireccion().getNombre().toLowerCase().contains("fiscal")) {
       Session s = null;
       try {
         s = HibernateUtil.getSessionFactory().openSession();
         Transaction tr = s.beginTransaction();
         Persona p = (Persona) beanVO;
         p.setDireccionFiscal(d);
         s.update(beanVO);
         tr.commit();
       } catch (Exception ex) {
         ex.printStackTrace();
       } finally {
         s.close();
       }
       break;
     }
   }
   return r;
 }
示例#15
0
  @Override
  public List<Forum> getForumsOfaUser(int userId) {
    // TODO Auto-generated method stub
    List<Forum> forums = new ArrayList<Forum>();
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      Query query = session.createQuery("from Subscription where userId = :userId");
      query.setString("userId", String.valueOf(userId));
      List<Subscription> userSubscribedGroups = query.list();
      for (Subscription subsc : userSubscribedGroups) {
        query = session.createQuery("from Forum where forumId = :forumId");
        query.setParameter("forumId", subsc.getForumId());
        // add this to a list variable query.uniqueResult();
        forums.add((Forum) query.uniqueResult());
      }

    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return forums;
  }
  protected Dairy createDairy(String dairyNumber, String licenseeName) {
    Session session;
    Transaction transaction;

    Dairy dairy;
    Location location;

    session = getOrCreateSession();
    transaction = session.beginTransaction();

    location = ModelFactory.eINSTANCE.createLocation();
    location.setDescriptiveLocation(null);
    location.setMapLocation(null);
    location.setPostalLocation(null);
    location.setStatutoryLocation(null);
    session.persist(location);

    dairy = DairyFactory.eINSTANCE.createDairy();
    dairy.setRegistrationNumber(dairyNumber);
    dairy.setLegalName(licenseeName);
    // dairy.setCompanyId(getDairyId());

    dairy.setDescription("<description>");
    dairy.setCompanyName("<company common name>");
    dairy.setPhoneNumber("+254 0072 0000 0000");
    dairy.setEstablishedDate(new Date(1, 1, 1975));

    dairy.setLocation(location);
    session.persist(dairy);

    transaction.commit();

    return dairy;
  }
示例#17
0
 public List<User> getUserSearchResults(int topicId) {
   // TODO Auto-generated method stub
   List<User> userArr = new ArrayList<User>();
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query1 = session.createQuery("select userId from UserTopic where topicId = :topicId");
     query1.setString("topicId", String.valueOf(topicId));
     Query query2 = session.createQuery("from User where userId in (:userList)");
     query2.setParameterList("userList", query1.list());
     userArr = query2.list();
     /*for(Topic topic : topicArr){
     	System.out.println("Topic Description----"+topic.getTopicDescription());
     	System.out.println("Topic Id----"+topic.getTopicId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return userArr;
 }
示例#18
0
  @Test
  public void testUseOfMultipleCustomFieldBridgeInstances() throws Exception {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    // Rather complex code here as we're not exposing the #withFieldBridge methods on the public
    // interface
    final ConnectedTermMatchingContext field1Context =
        (ConnectedTermMatchingContext) monthQb.keyword().onField(MonthClassBridge.FIELD_NAME_1);

    final ConnectedTermMatchingContext field2Context =
        (ConnectedTermMatchingContext)
            field1Context
                .withFieldBridge(new String2FieldBridgeAdaptor(new RomanNumberFieldBridge()))
                .andField(MonthClassBridge.FIELD_NAME_2);

    Query query =
        field2Context
            .withFieldBridge(new String2FieldBridgeAdaptor(new RomanNumberFieldBridge()))
            .matching(2)
            .createQuery();

    assertEquals(1, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());
    transaction.commit();
  }
  public void updateStaff(StaffEntity staff) {
    Session session = SessionFactoryProvider.getSessionFactory().openSession();

    Transaction dbTransaction = null;
    try {
      dbTransaction = session.beginTransaction();

      StaffEntity staffUpdate = (StaffEntity) session.get(StaffEntity.class, staff.getStaffId());

      log.info("Updating: " + staffUpdate.toString());

      staffUpdate.setFireNumber(staff.getFireNumber());
      staffUpdate.setFirstName(staff.getFirstName());
      staffUpdate.setLastName(staff.getLastName());
      staffUpdate.setRank(staff.getRank());
      staffUpdate.setHireDate(staff.getHireDate());
      staffUpdate.setTermDate(staff.getTermDate());
      staffUpdate.setDepartmentId(staff.getDepartmentId());

      session.update(staffUpdate);
      dbTransaction.commit();

    } catch (HibernateException error) {
      if (dbTransaction != null) dbTransaction.rollback();
      error.printStackTrace();
    } finally {
      session.close();
    }
  }
示例#20
0
  @Test
  public void testTermQueryOnAnalyzer() throws Exception {
    Transaction transaction = fullTextSession.beginTransaction();
    final QueryBuilder monthQb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Month.class).get();

    // regular term query
    Query query = monthQb.keyword().onField("mythology").matching("cold").createQuery();

    assertEquals(0, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());

    // term query based on several words
    query = monthQb.keyword().onField("mythology").matching("colder darker").createQuery();

    assertEquals(1, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());

    // term query applying the analyzer and generating one term per word
    query = monthQb.keyword().onField("mythology_stem").matching("snowboard").createQuery();

    assertEquals(1, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());

    // term query applying the analyzer and generating several terms per word
    query = monthQb.keyword().onField("mythology_ngram").matching("snobored").createQuery();

    assertEquals(1, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());

    // term query not using analyzers
    query = monthQb.keyword().onField("mythology").ignoreAnalyzer().matching("Month").createQuery();

    assertEquals(0, fullTextSession.createFullTextQuery(query, Month.class).getResultSize());

    transaction.commit();
  }
示例#21
0
文件: Dkkh.java 项目: sumodream/demo2
  public String dkkh1() {
    ActionContext ac = ActionContext.getContext();
    Map sess = ac.getSession();
    Ln001 l02 = (Ln001) sess.get("l01");

    l005.setAPPRNUM(l02.getAPPRNUM());
    l005.setAGENCYBANK(l02.getAGENCYBANK());
    l005.setACCTYPE("1");
    if (l02.getRETLOANCYCLE().equals("1")) {
      l005.setCURDAYBAL(hs.Debj(l02.getAPPRLOANSUM(), l02.getAPPRLOANTERM(), l005.getCURRATE()));
    } else {
      l005.setCURDAYBAL(hs.Debx(l02.getAPPRLOANSUM(), l02.getAPPRLOANTERM(), l005.getCURRATE()));
    }
    Date d = new Date();
    // SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
    l005.setBEGININTDATE(new java.sql.Date(d.getTime()));
    org.hibernate.Session session = HibernateSessionFactory.getSession();
    session.save(l005);
    Transaction t = session.beginTransaction();
    try {
      t.commit();
      HibernateSessionFactory.closeSession();
      return "success";
    } catch (Exception e) {
      // TODO: handle exception
      System.out.println(e);
      HibernateSessionFactory.closeSession();
      return "break1";
    }
  }
示例#22
0
 @Override
 public List<Reply> getRepliesToPost(int postId) {
   // TODO Auto-generated method stub
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   List<Reply> replyArr = new ArrayList<Reply>();
   try {
     tx = session.beginTransaction();
     Query query =
         session.createQuery("from Reply where postId = :postId order by createdDate desc");
     query.setParameter("postId", postId);
     replyArr = query.list();
     /*			for(Reply reply : replyArr){
     	System.out.println("Reply - id----"+reply.getReplyId());
     	System.out.println("Reply - Description----"+reply.getDescription());
     	System.out.println("Reply - Post id----"+reply.getPostId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return replyArr;
 }
  public static void reservar(
      Hospede hospede, Apartamento apartamento, Date dt_inicio, Date dt_fim) {
    Session session = null;
    Transaction tx = null;

    try {
      SessionFactory factory = new Configuration().configure().buildSessionFactory();
      session = factory.openSession();

      tx = session.beginTransaction();
      Reserva reserva = new Reserva();
      reserva.setHospede(hospede);
      reserva.setApartamento(apartamento);
      reserva.setDataInicio(dt_inicio);
      reserva.setDataFim(dt_fim);
      session.save(reserva);

      /*Depois de salvar a RESERVA tem que mudar a situação do apartamento para não disponível*/
      // Apartamento apBd = ApartamentoDAO.buscarApartamento(apartamento.getId());
      // apBd.setDisponivel(false);
      session.update(apartamento);
      tx.commit();

    } catch (Exception e) {
      if (tx != null) tx.rollback();
      System.out.println("Erro: " + e.getMessage());
    } finally {
      session.close();
    }
  }
示例#24
0
 @Override
 public void deleteSubscription(int userId, int forumId) {
   // TODO Auto-generated method stub
   Session session = this.sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query =
         session.createQuery(
             "delete from Subscription where userId = :userId and forumId = :forumId");
     query.setParameter("userId", userId);
     query.setParameter("forumId", forumId);
     int result = query.executeUpdate();
     System.out.println("Execute query..");
     if (result > 0) {
       tx.commit();
       // System.out.println("Subscription Removed..");
     } else {
       // System.out.println("Subscription does not exist");
       tx.rollback();
     }
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
 }
  /**
   * Deletes all database entries based on the class where method is called.
   *
   * @return
   */
  public synchronized boolean deleteAll() {

    Session session = null;
    Transaction transaction = null;
    boolean errorResult = false;

    try {
      session = HibernateUtil.getCurrentSession();
      transaction = session.beginTransaction();
      SQLQuery query = session.createSQLQuery(DELETE_ALL + getTableName());
      query.executeUpdate();
      transaction.commit();
      return true;
    } catch (HibernateException exception) {
      rollback(transaction);
      BookingLogger.getDefault()
          .severe(this, Messages.METHOD_DELETE_ALL, Messages.HIBERNATE_FAILED, exception);
      return errorResult;
    } catch (RuntimeException exception) {
      rollback(transaction);
      BookingLogger.getDefault()
          .severe(this, Messages.METHOD_DELETE_ALL, Messages.GENERIC_FAILED, exception);
      return errorResult;
    } finally {
      closeSession();
    }
  }
示例#26
0
  public int getCountOfSubscribers(int forumId, int userId) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.openSession();
    Transaction tx = null;
    int countOfSubscribers = 0;
    try {
      tx = session.beginTransaction();
      Query query = null;
      if (userId == 0) {
        query = session.createQuery("select count(*) from Subscription where forumId = :forumId");
        query.setParameter("forumId", forumId);
      } else {
        query =
            session.createQuery(
                "select count(*) from Subscription where forumId = :forumId and userId = :userId");
        query.setParameter("forumId", forumId);
        query.setParameter("userId", userId);
      }

      Long count = (Long) query.uniqueResult();
      countOfSubscribers = count.intValue();
      // System.out.println("No of subscribers.."+countOfSubscribers);
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return countOfSubscribers;
  }
示例#27
0
 @Override
 public void createProfessor(Professor professor) throws Exception {
   if (professor == null) {
     throw new NullPointerException("Professor is null");
   }
   if (professor.getUser() == null) {
     throw new NullPointerException("Field 'user' in Professor is null");
   }
   if (professor.getUser().getProfessor() == null) {
     throw new NullPointerException(
         "Field 'professor' in Professor.getUserForRedirect().professor " + "is null");
   }
   Session session = sessionFactory.openSession();
   Transaction transaction = session.getTransaction();
   transaction.begin();
   try {
     session.save(professor);
     transaction.commit();
     session.close();
   } catch (ConstraintViolationException e) {
     transaction.rollback();
     session.close();
     e.printStackTrace();
     throw new Exception("Login or Email already exists");
   }
 }
示例#28
0
  @Override
  public void saveEventDetails(Event event) {
    // TODO Auto-generated method stub

    // Opening a session to create a database connection
    Session session = this.sessionFactory.openSession();

    // for CRUD operations, we need to create a transaction
    Transaction tx = null;

    // adding a try catch block for maintaining the atomicity of transaction
    try {
      tx = session.beginTransaction();
      System.out.println("DbHelper..saveEventDetails");

      // session save inserts the object into DB
      session.save(event);

      tx.commit();
      System.out.println("Event saved");
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
  }
示例#29
0
 @Override
 public Organization delete(long id) {
   Session session = null;
   Transaction transaction = null;
   Organization organization = null;
   try {
     session = sessionFactory.openSession();
     transaction = session.beginTransaction();
     organization = (Organization) session.get(Organization.class, id);
     if (organization == null) {
       throw new HibernateException("Can't find organization record with id = " + id);
     } else if (organization.getPersons() != null && organization.getPersons().size() != 0) {
       organization = null;
       throw new HibernateException(
           "Can't delete organization record because it contains members.");
     }
     session.delete(organization);
     transaction.commit();
   } catch (HibernateException e) {
     if (transaction != null) {
       transaction.rollback();
     }
   } finally {
     if (session != null) {
       session.close();
     }
   }
   return organization;
 }
  /** @param args */
  public static void main(String[] args) {
    Session session = HibernateUtility.getSession();
    Transaction tx = session.beginTransaction();

    EmployeePojo emp1 = new EmployeePojo();

    emp1.setName("Ramu");
    emp1.setSalary(1500);
    session.save(emp1);

    EmployeePojo emp2 = new EmployeePojo();

    emp2.setName("Rakesh");
    emp2.setSalary(2500);
    session.save(emp2);

    EmployeePojo emp3 = new EmployeePojo();

    emp3.setName("Ravi");
    emp3.setSalary(3500);
    session.save(emp3);

    tx.commit();
    session.close();
  }