@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; }
@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(); }
@Override public void create(List<Statistics> statistics) { Session session = sessionFactory.getCurrentSession(); for (Statistics stat : statistics) { session.persist(stat); } }
@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; }
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; }
// 此方法用于动态条件查询 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; } }
/** * 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(); } }
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); } } }
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"; } }
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(); } }
@Override @Transactional public void modifierQualification(Qualification qualification) { // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); session.update(qualification); }
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; }
/** * 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(); }
/** * 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(); }
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(); }
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 { } }
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(); } }
@SuppressWarnings("unchecked") @Override public List<T> findAll() { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("FROM " + this.persistentClass.getName()); return (List<T>) query.list(); }
/** * 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(); } }
public int addExpression(Expression expression) { Session session = sessionManager.getCurrentSession(); Integer id = (Integer) session.save(expression); return id.intValue(); }
@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(); } } }
public Expression getExpression(int id) { Session session = sessionManager.getCurrentSession(); Expression expression = (Expression) session.get(Expression.class, new Integer(id)); return expression; }
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; }
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()"); } }
@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"); } }
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; }
@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; }
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(); }
@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; }
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; }