コード例 #1
0
 @Override
 public User getLikesCommentsAndBlogs(User user) {
   Session session = factory.openSession();
   @SuppressWarnings("unchecked")
   List<Long> like =
       session
           .createQuery("Select l.blogId from Likes as l where l.userId = :userId")
           .setParameter("userId", user.getUserId())
           .list();
   @SuppressWarnings("unchecked")
   List<Long> blog =
       session
           .createQuery("Select b.blogId from Blog as b where b.userId = :userId")
           .setParameter(":userId", user.getUserId())
           .list();
   @SuppressWarnings("unchecked")
   List<Long> comment =
       session
           .createQuery("Seelct c.commentId from Comment as c where c.userId = :userId")
           .setParameter(":userId", user.getUserId())
           .list();
   Set<Long> likeList = new HashSet<Long>(like);
   Set<Long> blogList = new HashSet<Long>(blog);
   Set<Long> commentList = new HashSet<Long>(comment);
   user.setLikes(likeList);
   user.setBlogs(blogList);
   user.setComments(commentList);
   return user;
 }
コード例 #2
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();
 }
コード例 #3
0
 @Override
 public void create(List<Statistics> statistics) {
   Session session = sessionFactory.getCurrentSession();
   for (Statistics stat : statistics) {
     session.persist(stat);
   }
 }
コード例 #4
0
  @Override
  public Almacen actualiza(Almacen almacen, Usuario usuario) {
    Session session = currentSession();
    if (usuario != null) {
      almacen.setEmpresa(usuario.getEmpresa());
    }
    try {
      // Actualiza la almacen
      log.debug("Actualizando almacen");
      session.update(almacen);
      session.flush();

    } catch (NonUniqueObjectException e) {
      try {
        session.merge(almacen);
      } catch (Exception ex) {
        log.error("No se pudo actualizar la almacen", ex);
        throw new RuntimeException("No se pudo actualizar la almacen", ex);
      }
    }
    if (usuario != null) {
      usuario.setAlmacen(almacen);
    }
    session.flush();
    return almacen;
  }
コード例 #5
0
ファイル: RateCodesDAO.java プロジェクト: muraleekrish/pric
 public Collection getAllRateCodes(int tdspId) {
   /**
    * Requires - Modifies - Effects -
    *
    * @throws -
    */
   Criteria objCriteria = null;
   Session objSession = null;
   List objList = null;
   try {
     logger.info("GETTING ALL RATE CODES BY TDSP ID");
     objSession = HibernateUtil.getSession();
     objCriteria =
         objSession
             .createCriteria(RateCodesVO.class)
             .add(Restrictions.eq("tdsp.tdspIdentifier", new Integer(tdspId)));
     objCriteria.addOrder(Order.asc("rateCode"));
     objList = objCriteria.list();
     logger.info("GOT ALL RATE CODES BY TDSP ID");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL RATE CODES BY TDSP ID", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objList;
 }
コード例 #6
0
 // 此方法用于动态条件查询
 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;
   }
 }
コード例 #7
0
  /**
   * 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();
    }
  }
コード例 #8
0
ファイル: SQLiteManager.java プロジェクト: ridoo/SOS
 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);
     }
   }
 }
コード例 #9
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";
    }
  }
コード例 #10
0
  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();
    }
  }
コード例 #11
0
 @Override
 @Transactional
 public void modifierQualification(Qualification qualification) {
   // TODO Auto-generated method stub
   Session session = sessionFactory.getCurrentSession();
   session.update(qualification);
 }
コード例 #12
0
  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;
  }
コード例 #13
0
  /**
   * Tìm kiếm nhanh
   *
   * @param c Tiêu chí tìm kiếm
   * @return Danh sách các điện thoại thỏa tiêu chí tìm kiếm
   */
  @SuppressWarnings("unchecked")
  public List<DienThoai> quickSearch(QuickSearchCriteria c) {

    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(DienThoai.class);

    if (c.getIdHangDienThoai() > 0) {
      Criterion manufacture = Restrictions.eq("hangDienThoai.id", c.getIdHangDienThoai());
      criteria.add(manufacture);
    }

    if (c.getTenDienThoai() != null) {
      Criterion name = Restrictions.like("ten", "%" + c.getTenDienThoai() + "%");
      criteria.add(name);
    }

    if (c.getGiaTu() >= 0.0) {
      Criterion minPrice = Restrictions.ge("giaHienHanh", c.getGiaTu());
      criteria.add(minPrice);
    }

    if (c.getGiaDen() >= 0.0) {
      Criterion maxPrice = Restrictions.le("giaHienHanh", c.getGiaDen());
      criteria.add(maxPrice);
    }
    criteria.add(Restrictions.eq("xoa", false));

    return criteria.list();
  }
コード例 #14
0
  /**
   * Tìm kiếm nhanh
   *
   * @param idHangDienThoai id của HangDienThoai.
   * @param ten tên DienThoai.
   * @param giaTu giá chặn dưới.
   * @param giaDen giá chặn trên.
   * @return Danh sách DienThoai thỏa tiêu chí tìm kiếm.
   */
  @SuppressWarnings("unchecked")
  public List<DienThoai> quickSearch(int idHangDienThoai, String ten, double giaTu, double giaDen) {

    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(DienThoai.class);

    if (idHangDienThoai > 0) {
      Criterion manufacture = Restrictions.eq("hangDienThoai.id", idHangDienThoai);
      criteria.add(manufacture);
    }

    if (ten != null) {
      Criterion name = Restrictions.like("ten", "%" + ten + "%");
      criteria.add(name);
    }

    if (giaTu >= 0.0) {
      Criterion minPrice = Restrictions.ge("giaHienHanh", giaTu);
      criteria.add(minPrice);
    }

    if (giaDen >= 0.0) {
      Criterion maxPrice = Restrictions.le("giaHienHanh", giaDen);
      criteria.add(maxPrice);
    }
    criteria.add(Restrictions.eq("xoa", false));

    return criteria.list();
  }
コード例 #15
0
 public void deleteDonViTinhTen(String dvtTen) {
   session.beginTransaction();
   String sql = "update DonViTinh set daXoa = 1 where dvtTen = '" + dvtTen + "'";
   Query query = session.createQuery(sql);
   query.executeUpdate();
   session.getTransaction().commit();
 }
コード例 #16
0
  public void insertTarjetaHistorico(PsTarjeta tarjeta, String xml) {

    try {

      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session newSession = sessionFactory.openSession();

      newSession.beginTransaction();
      ArmResponsePsTarjeta j = new ArmResponsePsTarjeta();
      j.setIdTarjetaArm(tarjeta.getIDTarjetaARM());
      j.setIdTarjetaFrida(tarjeta.getIDTarjetaFrida());
      j.setNombreTarjeta(tarjeta.getNombreTarjeta());
      j.setMeesageId(tarjeta.getMeesageID());
      j.setXmlMessage(xml);
      j.setFechaMensaje(new Date());

      newSession.persist(j);

      newSession.getTransaction().commit();
      newSession.close();

    } catch (HibernateException e) {

    } finally {

    }
  }
コード例 #17
0
  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();
    }
  }
コード例 #18
0
ファイル: GenericDaoImpl.java プロジェクト: juancte1986/tp2
 @SuppressWarnings("unchecked")
 @Override
 public List<T> findAll() {
   Session session = sessionFactory.getCurrentSession();
   Query query = session.createQuery("FROM " + this.persistentClass.getName());
   return (List<T>) query.list();
 }
コード例 #19
0
  /**
   * 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();
    }
  }
コード例 #20
0
  public int addExpression(Expression expression) {
    Session session = sessionManager.getCurrentSession();

    Integer id = (Integer) session.save(expression);

    return id.intValue();
  }
コード例 #21
0
ファイル: StoreDaoImpl.java プロジェクト: RAZER-KIEV/proff25
 @Override
 public Map<Vendor, List<Notebook>> getNotebooksStorePresent() {
   Session session = factory.openSession();
   try {
     Query query = session.createQuery("select n from Store s join s.notebook n");
     List results = query.list();
     Map<Vendor, List<Notebook>> resMap = new HashMap<>();
     for (Iterator iter = results.iterator(); iter.hasNext(); ) {
       Notebook notebook = (Notebook) iter.next();
       Vendor key = notebook.getVendor();
       if (resMap.containsKey(key)) {
         List<Notebook> notebooks = resMap.get(key);
         notebooks.add(notebook);
         resMap.replace(key, notebooks);
       } else {
         List<Notebook> notebooks = new ArrayList<>();
         notebooks.add(notebook);
         resMap.put(key, notebooks);
       }
     }
     return resMap;
   } finally {
     if (session != null) {
       session.close();
     }
   }
 }
コード例 #22
0
  public Expression getExpression(int id) {
    Session session = sessionManager.getCurrentSession();

    Expression expression = (Expression) session.get(Expression.class, new Integer(id));

    return expression;
  }
コード例 #23
0
ファイル: RateCodesDAO.java プロジェクト: muraleekrish/pric
 public HashMap getAllRateCodes() {
   /**
    * Requires - Modifies - Effects -
    *
    * @throws -
    */
   Criteria objCriteria = null;
   Session objSession = null;
   Integer totRecordCount = null;
   List objList = null;
   HashMap hmResult = new HashMap();
   try {
     logger.info("GETTING ALL RATE CODES");
     objSession = HibernateUtil.getSession();
     objCriteria = objSession.createCriteria(RateCodesVO.class);
     totRecordCount = new Integer(objCriteria.list().size());
     objList = objCriteria.list();
     hmResult.put("TotalRecordCount", totRecordCount);
     hmResult.put("Records", objList);
     logger.info("GOT ALL RATE CODES");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL RATE CODES", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return hmResult;
 }
コード例 #24
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()");
    }
  }
コード例 #25
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");
   }
 }
コード例 #26
0
 public int lastInsertId() {
   session.beginTransaction();
   String sql = "select MAX(dvtId) from DonViTinh";
   int dvtId = (int) session.createQuery(sql).list().get(0);
   session.getTransaction().commit();
   return dvtId;
 }
コード例 #27
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;
 }
コード例 #28
0
 public void deleteDonViTinh(int dvtId) {
   session.beginTransaction();
   String sql = "update DonViTinh set daXoa = 1 where dvtId = " + dvtId;
   Query query = session.createQuery(sql);
   query.executeUpdate();
   session.getTransaction().commit();
 }
コード例 #29
0
 @Override
 public List<Statistics> getByBookId(int id) {
   Session session = sessionFactory.getCurrentSession();
   Criteria criteria = session.createCriteria(Statistics.class);
   List<Statistics> statistics = criteria.add(Restrictions.eq("book.id", id)).list();
   return statistics;
 }
コード例 #30
0
  public IKategorie getKategorie(String kategorieName) throws DatabaseEntryNotFoundException {

    IKategorie kategorie = null;

    try {
      Session session = HibernateHelper.getSession();
      Query query =
          session.createQuery("from " + getTable() + " k where k.bezeichnung = :kategorieName");
      query.setString("kategorieName", kategorieName);

      @SuppressWarnings("rawtypes")
      List results = query.list();

      if (results.size() == 1) {
        kategorie = (IKategorie) results.get(0);
      }

      if (results.size() == 0) {
        throw new DatabaseEntryNotFoundException();
      }

    } catch (HibernateException e) {
      e.printStackTrace();
    }

    return kategorie;
  }