List of usage examples for org.hibernate.criterion Projections projectionList
public static ProjectionList projectionList()
From source file:it.unitn.elisco.dao.CourseDAO.java
public List<CourseBasics> getCourseSubscriptions(Student student) { Student_CourseDAO scdao = new Student_CourseDAO(); CourseDAO cdao = new CourseDAO(); Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Get all courses Criteria criteria = s.createCriteria(Course.class); criteria.add(Restrictions.eq("open_subscription", true)); criteria.createAlias("sector", "sec"); criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id") .add(Projections.property("name"), "name").add(Projections.property("sec.cssClassName"), "sector")) .setResultTransformer(Transformers.aliasToBean(CourseBasics.class)); List<CourseBasics> res = criteria.list(); for (CourseBasics course : res) { course.setSubscribed(scdao.getSubscription(s, student, cdao.findCourse(s, course.getId())) != null); }// www. j a v a2 s . co m tx.commit(); s.close(); return res; }
From source file:it.unitn.elisco.dao.CourseDAO.java
private ContextBasics getCurrentContextBasics(Session s, Course course) { DetachedCriteria maxId = DetachedCriteria.forClass(Context.class).add(Restrictions.eq("course", course)) .setProjection(Projections.max("id")); Criteria criteria = s.createCriteria(Context.class); criteria.add(Property.forName("id").eq(maxId)); criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id") .add(Projections.property("title"), "title").add(Projections.property("subtitle"), "subtitle")) .setResultTransformer(Transformers.aliasToBean(ContextBasics.class)); return (ContextBasics) criteria.uniqueResult(); }
From source file:it.unitn.elisco.dao.SectorDAO.java
public List<SectorBasics> findSectorBasics(String sector) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Get all sectors // - which id begin with the specified query string (optional, otherwise return all sectors) Criteria criteria = s.createCriteria(Sector.class); if (sector != null && !sector.equals("")) { criteria.add(Restrictions.like("id", sector, MatchMode.START)); }//from w ww . j a v a 2 s . co m criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id") .add(Projections.property("description"), "description")) .setResultTransformer(Transformers.aliasToBean(SectorBasics.class)); List<SectorBasics> res = criteria.list(); tx.commit(); s.close(); return res; }
From source file:it.unitn.elisco.dao.StudentDAO.java
public List<PersonBasics> findStudents(String emailLike) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch students: // - which are confirmed (confirmation_token is null) // - which email begins with the specified query (optional, otherwise return all students) Criteria criteria = s.createCriteria(Student.class); criteria.add(Restrictions.isNull("confirmation_token")); if (emailLike != null && emailLike != "") { criteria.add(Restrictions.like("email", emailLike, MatchMode.START)); }//from w ww .ja v a2s . com // Then return results as PersonBasics objects criteria.setProjection(Projections.projectionList().add(Projections.property("name"), "name") .add(Projections.property("surname"), "surname").add(Projections.property("email"), "email")); criteria.setResultTransformer(Transformers.aliasToBean(PersonBasics.class)); List<PersonBasics> res = criteria.list(); tx.commit(); s.close(); return res; }
From source file:ke.co.mspace.nonsmppmanager.service.SMSOutServiceImpl.java
@Override public Map<String, Object> smsOutGroupBy(String user, String startDate, String endDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.getTransaction().begin();/*from ww w . j a v a2 s . c om*/ Criteria criteria = session.createCriteria(SMSOut.class); /* * This is where the report is going to come from * projectionList.add(Projections.sqlGroupProjection("YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as monthSubmitted, time_submitted as timeSubmitted", "timeSubmitted", new String[] { "monthSubmitted", "timeSubmitted", "yearSubmitted" }, new Type[] { StandardBasicTypes.STRING })); */ ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.sqlGroupProjection( "YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as timeSubmitted", "yearSubmitted, timeSubmitted", new String[] { "yearSubmitted", "timeSubmitted" }, new Type[] { StandardBasicTypes.LONG, StandardBasicTypes.STRING })); projectionList.add(Projections.rowCount()); criteria.setProjection(projectionList); //This is added criteria.add(Restrictions.eq("user", user)); criteria.addOrder(Order.asc("timeSubmitted")); criteria.add(Restrictions.between("timeSubmitted", startDate, endDate)); List<Object[]> results = criteria.list(); for (Object[] aResult : results) { System.out.println("the Object: " + Arrays.deepToString(aResult)); System.out.println("Year : " + aResult[0] + " Month : " + aResult[1] + " No. Sent : " + aResult[2]); } Map<String, Object> mapResult = new HashMap<>(); mapResult.put("result", results); mapResult.put("noSMS", 20); session.getTransaction().commit(); return mapResult; }
From source file:ke.co.mspace.nonsmppmanager.service.SMSOutServiceImpl.java
@Override public Map<String, String> smsOutGroupByUser(String startDate, String endDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.getTransaction().begin();/*from www . j a v a 2s . co m*/ Criteria criteria = session.createCriteria(SMSOut.class); Calendar startAnotherDate = null; Calendar endAnotherDate = null; try { startAnotherDate = stringToCalendar(startDate); endAnotherDate = stringToCalendar(endDate); } catch (ParseException ex) { Logger.getLogger(SMSOutServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } /* * This is where the report is going to come from * projectionList.add(Projections.sqlGroupProjection("YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as monthSubmitted, time_submitted as timeSubmitted", "timeSubmitted", new String[] { "monthSubmitted", "timeSubmitted", "yearSubmitted" }, new Type[] { StandardBasicTypes.STRING })); */ ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.sqlGroupProjection( "YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as timeSubmitted, user as userName", "yearSubmitted, timeSubmitted, userName", new String[] { "yearSubmitted", "timeSubmitted", "userName" }, new Type[] { StandardBasicTypes.LONG, StandardBasicTypes.STRING, StandardBasicTypes.STRING })); projectionList.add(Projections.rowCount()); criteria.setProjection(projectionList); criteria.addOrder(Order.asc("timeSubmitted")); criteria.add(Restrictions.between("timeSubmitted", startDate, endDate)); List<Object[]> results = criteria.list(); Map<String, Integer> json = new LinkedHashMap<>(); Set<String> months = new LinkedHashSet<>(); Set<String> users = new LinkedHashSet<>(); while (startAnotherDate.before(endAnotherDate)) { String month = startAnotherDate.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()); int year = startAnotherDate.get(Calendar.YEAR); for (Object[] aResult : results) { json.put(year + "-" + month + "-" + aResult[2], 0); months.add(aResult[0] + "-" + aResult[1]); users.add(String.valueOf(aResult[2])); } startAnotherDate.add(Calendar.MONTH, 1); } String madeUp = null; for (String aString : json.keySet()) { for (Object[] aResult : results) { madeUp = aResult[0] + "-" + aResult[1] + "-" + aResult[2]; if (aString.equals(madeUp)) { json.put(aString, Integer.parseInt(String.valueOf(aResult[3]))); } } } StringBuilder builder = new StringBuilder(); for (String aMonth : months) { builder.append("["); builder.append('"'); builder.append(aMonth.substring(0, 8)); builder.append('"'); builder.append(','); for (String aString : json.keySet()) { if (aString.contains(aMonth)) { builder.append(json.get(aString)); builder.append(","); } } builder.append("]"); if (builder.length() > 0) { if (builder.charAt(builder.lastIndexOf("]") - 1) == ',') { builder.deleteCharAt(builder.lastIndexOf("]") - 1); } } builder.append(","); } if (builder.length() > 0) { builder.deleteCharAt(builder.lastIndexOf(",")); } StringBuilder userBuilder = new StringBuilder(); userBuilder.append("["); for (String aUser : users) { userBuilder.append('"'); userBuilder.append(aUser); userBuilder.append('"'); userBuilder.append(','); } userBuilder.append(']'); if (userBuilder.length() > 0) { if (userBuilder.charAt(userBuilder.lastIndexOf("]") - 1) == ',') { userBuilder.deleteCharAt(userBuilder.lastIndexOf("]") - 1); } } System.out.println("A new builder : " + builder.toString()); System.out.println("The Users : " + userBuilder.toString()); Map<String, String> mapResult = new HashMap<>(); mapResult.put("data", builder.toString()); mapResult.put("users", userBuilder.toString()); session.getTransaction().commit(); return mapResult; }
From source file:kr.debop4j.access.test.repository.CriteriaSampleTest.java
License:Apache License
@Test @Transactional(readOnly = true)//from w ww . ja v a 2s .c o m public void groupingTest() { DetachedCriteria dc = DetachedCriteria.forClass(Employee.class); dc.createAlias("company", "c").createAlias("empGrade", "eg") .setProjection(Projections.projectionList().add(Projections.groupProperty("c.code")) .add(Projections.groupProperty("eg.code")).add(Projections.rowCount())); List loaded = dc.getExecutableCriteria(hibernateDao.getSession()).list(); log.info("Group by = [{}]", loaded); }
From source file:kr.debop4j.access.test.repository.CriteriaSampleTest.java
License:Apache License
@Test @Transactional(readOnly = true)//from w w w . j a v a 2s. com public void subqueriesTest() { DetachedCriteria memberSizeDc = DetachedCriteria.forClass(DepartmentMember.class); memberSizeDc.setProjection(Projections.projectionList().add(Projections.groupProperty("department")) .add(Projections.rowCount(), "count")).addOrder(Order.desc("count")); Object[] members = (Object[]) memberSizeDc.getExecutableCriteria(hibernateDao.getSession()).setMaxResults(1) .uniqueResult(); if (members != null) { Long departmentId = (Long) members[0]; DetachedCriteria dc = DetachedCriteria.forClass(Department.class); dc.add(Restrictions.eq("id", departmentId)); dc.getExecutableCriteria(UnitOfWorks.getCurrentSession()).list(); } }
From source file:kr.debop4j.access.test.repository.CriteriaSampleTest.java
License:Apache License
@Test @Transactional(readOnly = true)/*from w ww .j a v a 2 s .c o m*/ public void subqueriesTest2() { DetachedCriteria memberSizeDc = DetachedCriteria.forClass(DepartmentMember.class); memberSizeDc.setProjection(Projections.projectionList().add(Projections.groupProperty("department")) .add(Projections.rowCount(), "count")); DetachedCriteria dc = DetachedCriteria.forClass(Department.class); dc.add(Subqueries.propertyEq("id", memberSizeDc)); }
From source file:Mob.MobLoadMonthlySales.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from www . j ava2 s . c o m*/ PrintWriter pw = resp.getWriter(); DataInputStream ds = new DataInputStream(req.getInputStream()); String dfr = ds.readUTF(); String dto = ds.readUTF(); String cat = ds.readUTF(); String pcd = ds.readUTF(); ds.close(); String datefrmarr[] = dfr.split(" "); String datetoarr[] = dto.split(" "); Session con = FactoryManager.getSessionFactory().openSession(); List<Object[]> list; Criteria cri = con.createCriteria(TransProd.class); SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yyyy"); if (dfr != null && dto != null) { Criteria cri2 = cri.createCriteria("transaction"); if (!dfr.equals("")) { Date d = sdf.parse(datefrmarr[1] + "/" + datefrmarr[2] + "/" + datefrmarr[5]); cri2.add(Restrictions.ge("transDate", d)); } if (!dto.equals("")) { Date d = sdf.parse(datetoarr[1] + "/" + datetoarr[2] + "/" + datetoarr[5]); cri2.add(Restrictions.le("transDate", d)); } } cri.setProjection(Projections.projectionList().add(Projections.groupProperty("stock")) .add(Projections.count("qty"))); // cri.createAlias("stock", "s").add(Projections.groupProperty("s.batchid")); list = cri.list(); String out = ""; double subtot = 0.0; for (Object[] obj : list) { Stock stk = (Stock) obj[0]; long qty = (Long) obj[1]; if (!pcd.equals("All")) { if (stk.getProducts().getProdCode().equals(pcd)) { out += "Product Code : " + stk.getProducts().getProdCode(); out += " "; out += "Batch ID : " + stk.getBatchid(); out += " "; out += "Product Name : " + stk.getProducts().getBrand().getBrandName() + " " + stk.getProducts().getItmName(); out += " "; out += "Quantity : " + qty; out += " "; out += "Price : " + stk.getItmPrice(); out += " "; out += "Discount : " + stk.getDiscount(); out += " "; out += "Total : " + (stk.getItmPrice() - stk.getDiscount()) * qty; subtot += (stk.getItmPrice() - stk.getDiscount()) * qty; out += ","; } } else if (!cat.equals("0")) { if (stk.getProducts().getCategory().getIdcat().equals(Integer.parseInt(cat))) { out += "Product Code : " + stk.getProducts().getProdCode(); out += " "; out += "Batch ID : " + stk.getBatchid(); out += " "; out += "Product Name : " + stk.getProducts().getBrand().getBrandName() + " " + stk.getProducts().getItmName(); out += " "; out += "Quantity : " + qty; out += " "; out += "Price : " + stk.getItmPrice(); out += " "; out += "Discount : " + stk.getDiscount(); out += " "; out += "Total : " + (stk.getItmPrice() - stk.getDiscount()) * qty; subtot += (stk.getItmPrice() - stk.getDiscount()) * qty; out += ","; } } else { out += "Product Code : " + stk.getProducts().getProdCode(); out += " "; out += "Batch ID : " + stk.getBatchid(); out += " "; out += "Product Name : " + stk.getProducts().getBrand().getBrandName() + " " + stk.getProducts().getItmName(); out += " "; out += "Quantity : " + qty; out += " "; out += "Price : " + stk.getItmPrice(); out += " "; out += "Discount : " + stk.getDiscount(); out += " "; out += "Total : " + (stk.getItmPrice() - stk.getDiscount()) * qty; subtot += (stk.getItmPrice() - stk.getDiscount()) * qty; out += ","; } } out += "Sub Total : Rs." + subtot; out += ","; pw.print(out); } catch (Exception e) { e.printStackTrace(); } }