Search in sources :

Example 1 with Projection

use of org.hibernate.criterion.Projection in project hibernate-orm by hibernate.

the class CriteriaQueryTest method testProjections.

@Test
public void testProjections() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Course course = new Course();
    course.setCourseCode("HIB");
    course.setDescription("Hibernate Training");
    s.save(course);
    Student gavin = new Student();
    gavin.setName("Gavin King");
    gavin.setStudentNumber(667);
    s.save(gavin);
    Student xam = new Student();
    xam.setName("Max Rydahl Andersen");
    xam.setStudentNumber(101);
    s.save(xam);
    Enrolment enrolment = new Enrolment();
    enrolment.setCourse(course);
    enrolment.setCourseCode(course.getCourseCode());
    enrolment.setSemester((short) 1);
    enrolment.setYear((short) 1999);
    enrolment.setStudent(xam);
    enrolment.setStudentNumber(xam.getStudentNumber());
    xam.getEnrolments().add(enrolment);
    s.save(enrolment);
    enrolment = new Enrolment();
    enrolment.setCourse(course);
    enrolment.setCourseCode(course.getCourseCode());
    enrolment.setSemester((short) 3);
    enrolment.setYear((short) 1998);
    enrolment.setStudent(gavin);
    enrolment.setStudentNumber(gavin.getStudentNumber());
    gavin.getEnrolments().add(enrolment);
    s.save(enrolment);
    //s.flush();
    Long count = (Long) s.createCriteria(Enrolment.class).setProjection(Projections.count("studentNumber").setDistinct()).uniqueResult();
    assertEquals(count, new Long(2));
    count = (Long) s.createCriteria(Enrolment.class).setProjection(Projections.countDistinct("studentNumber")).uniqueResult();
    assertEquals(count, new Long(2));
    count = (Long) s.createCriteria(Enrolment.class).setProjection(Projections.countDistinct("courseCode").as("cnt")).uniqueResult();
    assertEquals(count, new Long(1));
    Object object = s.createCriteria(Enrolment.class).setProjection(Projections.projectionList().add(Projections.count("studentNumber")).add(Projections.max("studentNumber")).add(Projections.min("studentNumber")).add(Projections.avg("studentNumber"))).uniqueResult();
    Object[] result = (Object[]) object;
    assertEquals(new Long(2), result[0]);
    assertEquals(new Long(667), result[1]);
    assertEquals(new Long(101), result[2]);
    assertEquals(384.0, ((Double) result[3]).doubleValue(), 0.01);
    List resultWithMaps = s.createCriteria(Enrolment.class).setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("studentNumber"), "stNumber").add(Projections.property("courseCode"), "cCode"))).add(Restrictions.gt("studentNumber", new Long(665))).add(Restrictions.lt("studentNumber", new Long(668))).addOrder(Order.asc("stNumber")).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
    assertEquals(1, resultWithMaps.size());
    Map m1 = (Map) resultWithMaps.get(0);
    assertEquals(new Long(667), m1.get("stNumber"));
    assertEquals(course.getCourseCode(), m1.get("cCode"));
    resultWithMaps = s.createCriteria(Enrolment.class).setProjection(Projections.property("studentNumber").as("stNumber")).addOrder(Order.desc("stNumber")).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
    assertEquals(2, resultWithMaps.size());
    Map m0 = (Map) resultWithMaps.get(0);
    m1 = (Map) resultWithMaps.get(1);
    assertEquals(new Long(101), m1.get("stNumber"));
    assertEquals(new Long(667), m0.get("stNumber"));
    List resultWithAliasedBean = s.createCriteria(Enrolment.class).createAlias("student", "st").createAlias("course", "co").setProjection(Projections.projectionList().add(Projections.property("st.name"), "studentName").add(Projections.property("co.description"), "courseDescription")).addOrder(Order.desc("studentName")).setResultTransformer(Transformers.aliasToBean(StudentDTO.class)).list();
    assertEquals(2, resultWithAliasedBean.size());
    StudentDTO dto = (StudentDTO) resultWithAliasedBean.get(0);
    assertNotNull(dto.getDescription());
    assertNotNull(dto.getName());
    s.createCriteria(Student.class).add(Restrictions.like("name", "Gavin", MatchMode.START)).addOrder(Order.asc("name")).createCriteria("enrolments", "e").addOrder(Order.desc("year")).addOrder(Order.desc("semester")).createCriteria("course", "c").addOrder(Order.asc("description")).setProjection(Projections.projectionList().add(Projections.property("this.name")).add(Projections.property("e.year")).add(Projections.property("e.semester")).add(Projections.property("c.courseCode")).add(Projections.property("c.description"))).uniqueResult();
    Projection p1 = Projections.projectionList().add(Projections.count("studentNumber")).add(Projections.max("studentNumber")).add(Projections.rowCount());
    Projection p2 = Projections.projectionList().add(Projections.min("studentNumber")).add(Projections.avg("studentNumber")).add(Projections.sqlProjection("1 as constOne, count(*) as countStar", new String[] { "constOne", "countStar" }, new Type[] { StandardBasicTypes.INTEGER, StandardBasicTypes.INTEGER }));
    Object[] array = (Object[]) s.createCriteria(Enrolment.class).setProjection(Projections.projectionList().add(p1).add(p2)).uniqueResult();
    assertEquals(array.length, 7);
    List list = s.createCriteria(Enrolment.class).createAlias("student", "st").createAlias("course", "co").setProjection(Projections.projectionList().add(Projections.groupProperty("co.courseCode")).add(Projections.count("st.studentNumber").setDistinct()).add(Projections.groupProperty("year"))).list();
    assertEquals(list.size(), 2);
    Object g = s.createCriteria(Student.class).add(Restrictions.idEq(new Long(667))).setFetchMode("enrolments", FetchMode.JOIN).uniqueResult();
    assertSame(g, gavin);
    s.delete(gavin);
    s.delete(xam);
    s.delete(course);
    t.commit();
    s.close();
}
Also used : Projection(org.hibernate.criterion.Projection) Type(org.hibernate.type.Type) Transaction(org.hibernate.Transaction) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) Session(org.hibernate.Session) Test(org.junit.Test)

Example 2 with Projection

use of org.hibernate.criterion.Projection in project hibernate-orm by hibernate.

the class CriteriaQueryTranslator method getColumnsUsingProjection.

/**
	 * Get the names of the columns constrained
	 * by this criterion.
	 */
@Override
public String[] getColumnsUsingProjection(Criteria subcriteria, String propertyName) throws HibernateException {
    //first look for a reference to a projection alias
    final Projection projection = rootCriteria.getProjection();
    String[] projectionColumns = null;
    if (projection != null) {
        projectionColumns = (projection instanceof EnhancedProjection ? ((EnhancedProjection) projection).getColumnAliases(propertyName, 0, rootCriteria, this) : projection.getColumnAliases(propertyName, 0));
    }
    if (projectionColumns == null) {
        //look for a property
        try {
            return getColumns(propertyName, subcriteria);
        } catch (HibernateException he) {
            //not found in inner query , try the outer query
            if (outerQueryTranslator != null) {
                return outerQueryTranslator.getColumnsUsingProjection(subcriteria, propertyName);
            } else {
                throw he;
            }
        }
    } else {
        //it refers to an alias of a projection
        return projectionColumns;
    }
}
Also used : HibernateException(org.hibernate.HibernateException) EnhancedProjection(org.hibernate.criterion.EnhancedProjection) Projection(org.hibernate.criterion.Projection) EnhancedProjection(org.hibernate.criterion.EnhancedProjection)

Example 3 with Projection

use of org.hibernate.criterion.Projection in project hibernate-orm by hibernate.

the class CriteriaQueryTranslator method getTypeUsingProjection.

@Override
public Type getTypeUsingProjection(Criteria subcriteria, String propertyName) throws HibernateException {
    //first look for a reference to a projection alias
    final Projection projection = rootCriteria.getProjection();
    Type[] projectionTypes = projection == null ? null : projection.getTypes(propertyName, subcriteria, this);
    if (projectionTypes == null) {
        try {
            //look for a property
            return getType(subcriteria, propertyName);
        } catch (HibernateException he) {
            //not found in inner query , try the outer query
            if (outerQueryTranslator != null) {
                return outerQueryTranslator.getType(subcriteria, propertyName);
            } else {
                throw he;
            }
        }
    } else {
        if (projectionTypes.length != 1) {
            //should never happen, i think
            throw new QueryException("not a single-length projection: " + propertyName);
        }
        return projectionTypes[0];
    }
}
Also used : StringRepresentableType(org.hibernate.type.StringRepresentableType) CollectionType(org.hibernate.type.CollectionType) JoinType(org.hibernate.sql.JoinType) AssociationType(org.hibernate.type.AssociationType) Type(org.hibernate.type.Type) QueryException(org.hibernate.QueryException) HibernateException(org.hibernate.HibernateException) EnhancedProjection(org.hibernate.criterion.EnhancedProjection) Projection(org.hibernate.criterion.Projection)

Example 4 with Projection

use of org.hibernate.criterion.Projection in project hibernate-orm by hibernate.

the class CriteriaQueryTest method testProjectionsUsingProperty.

@Test
public void testProjectionsUsingProperty() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Course course = new Course();
    course.setCourseCode("HIB");
    course.setDescription("Hibernate Training");
    course.getCourseMeetings().add(new CourseMeeting(course, "Monday", 1, "1313 Mockingbird Lane"));
    s.save(course);
    Student gavin = new Student();
    gavin.setName("Gavin King");
    gavin.setStudentNumber(667);
    CityState odessaWa = new CityState("Odessa", "WA");
    gavin.setCityState(odessaWa);
    gavin.setPreferredCourse(course);
    s.save(gavin);
    Student xam = new Student();
    xam.setName("Max Rydahl Andersen");
    xam.setStudentNumber(101);
    s.save(xam);
    Enrolment enrolment = new Enrolment();
    enrolment.setCourse(course);
    enrolment.setCourseCode(course.getCourseCode());
    enrolment.setSemester((short) 1);
    enrolment.setYear((short) 1999);
    enrolment.setStudent(xam);
    enrolment.setStudentNumber(xam.getStudentNumber());
    xam.getEnrolments().add(enrolment);
    s.save(enrolment);
    enrolment = new Enrolment();
    enrolment.setCourse(course);
    enrolment.setCourseCode(course.getCourseCode());
    enrolment.setSemester((short) 3);
    enrolment.setYear((short) 1998);
    enrolment.setStudent(gavin);
    enrolment.setStudentNumber(gavin.getStudentNumber());
    gavin.getEnrolments().add(enrolment);
    s.save(enrolment);
    s.flush();
    List resultList = s.createCriteria(Enrolment.class).setProjection(Projections.projectionList().add(Property.forName("student"), "student").add(Property.forName("course"), "course").add(Property.forName("semester"), "semester").add(Property.forName("year"), "year")).list();
    assertEquals(2, resultList.size());
    for (Iterator it = resultList.iterator(); it.hasNext(); ) {
        Object[] objects = (Object[]) it.next();
        assertEquals(4, objects.length);
        assertTrue(objects[0] instanceof Student);
        assertTrue(objects[1] instanceof Course);
        assertTrue(objects[2] instanceof Short);
        assertTrue(objects[3] instanceof Short);
    }
    resultList = s.createCriteria(Student.class).setProjection(Projections.projectionList().add(Projections.id().as("studentNumber")).add(Property.forName("name"), "name").add(Property.forName("cityState"), "cityState").add(Property.forName("preferredCourse"), "preferredCourse")).list();
    assertEquals(2, resultList.size());
    for (Iterator it = resultList.iterator(); it.hasNext(); ) {
        Object[] objects = (Object[]) it.next();
        assertEquals(4, objects.length);
        assertTrue(objects[0] instanceof Long);
        assertTrue(objects[1] instanceof String);
        if ("Gavin King".equals(objects[1])) {
            assertTrue(objects[2] instanceof CityState);
            assertTrue(objects[3] instanceof Course);
        } else {
            assertNull(objects[2]);
            assertNull(objects[3]);
        }
    }
    resultList = s.createCriteria(Student.class).add(Restrictions.eq("name", "Gavin King")).setProjection(Projections.projectionList().add(Projections.id().as("studentNumber")).add(Property.forName("name"), "name").add(Property.forName("cityState"), "cityState").add(Property.forName("preferredCourse"), "preferredCourse")).list();
    assertEquals(1, resultList.size());
    Object[] aResult = (Object[]) s.createCriteria(Student.class).add(Restrictions.idEq(new Long(667))).setProjection(Projections.projectionList().add(Projections.id().as("studentNumber")).add(Property.forName("name"), "name").add(Property.forName("cityState"), "cityState").add(Property.forName("preferredCourse"), "preferredCourse")).uniqueResult();
    assertNotNull(aResult);
    assertEquals(4, aResult.length);
    assertTrue(aResult[0] instanceof Long);
    assertTrue(aResult[1] instanceof String);
    assertTrue(aResult[2] instanceof CityState);
    assertTrue(aResult[3] instanceof Course);
    Long count = (Long) s.createCriteria(Enrolment.class).setProjection(Property.forName("studentNumber").count().setDistinct()).uniqueResult();
    assertEquals(count, new Long(2));
    Object object = s.createCriteria(Enrolment.class).setProjection(Projections.projectionList().add(Property.forName("studentNumber").count()).add(Property.forName("studentNumber").max()).add(Property.forName("studentNumber").min()).add(Property.forName("studentNumber").avg())).uniqueResult();
    Object[] result = (Object[]) object;
    assertEquals(new Long(2), result[0]);
    assertEquals(new Long(667), result[1]);
    assertEquals(new Long(101), result[2]);
    assertEquals(384.0, ((Double) result[3]).doubleValue(), 0.01);
    s.createCriteria(Enrolment.class).add(Property.forName("studentNumber").gt(new Long(665))).add(Property.forName("studentNumber").lt(new Long(668))).add(Property.forName("courseCode").like("HIB", MatchMode.START)).add(Property.forName("year").eq(new Short((short) 1999))).addOrder(Property.forName("studentNumber").asc()).uniqueResult();
    List resultWithMaps = s.createCriteria(Enrolment.class).setProjection(Projections.projectionList().add(Property.forName("studentNumber").as("stNumber")).add(Property.forName("courseCode").as("cCode"))).add(Property.forName("studentNumber").gt(new Long(665))).add(Property.forName("studentNumber").lt(new Long(668))).addOrder(Property.forName("studentNumber").asc()).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
    assertEquals(1, resultWithMaps.size());
    Map m1 = (Map) resultWithMaps.get(0);
    assertEquals(new Long(667), m1.get("stNumber"));
    assertEquals(course.getCourseCode(), m1.get("cCode"));
    resultWithMaps = s.createCriteria(Enrolment.class).setProjection(Property.forName("studentNumber").as("stNumber")).addOrder(Order.desc("stNumber")).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
    assertEquals(2, resultWithMaps.size());
    Map m0 = (Map) resultWithMaps.get(0);
    m1 = (Map) resultWithMaps.get(1);
    assertEquals(new Long(101), m1.get("stNumber"));
    assertEquals(new Long(667), m0.get("stNumber"));
    List resultWithAliasedBean = s.createCriteria(Enrolment.class).createAlias("student", "st").createAlias("course", "co").setProjection(Projections.projectionList().add(Property.forName("st.name").as("studentName")).add(Property.forName("co.description").as("courseDescription"))).addOrder(Order.desc("studentName")).setResultTransformer(Transformers.aliasToBean(StudentDTO.class)).list();
    assertEquals(2, resultWithAliasedBean.size());
    StudentDTO dto = (StudentDTO) resultWithAliasedBean.get(0);
    assertNotNull(dto.getDescription());
    assertNotNull(dto.getName());
    CourseMeeting courseMeetingDto = (CourseMeeting) s.createCriteria(CourseMeeting.class).setProjection(Projections.projectionList().add(Property.forName("id").as("id")).add(Property.forName("course").as("course"))).addOrder(Order.desc("id")).setResultTransformer(Transformers.aliasToBean(CourseMeeting.class)).uniqueResult();
    assertNotNull(courseMeetingDto.getId());
    assertEquals(course.getCourseCode(), courseMeetingDto.getId().getCourseCode());
    assertEquals("Monday", courseMeetingDto.getId().getDay());
    assertEquals("1313 Mockingbird Lane", courseMeetingDto.getId().getLocation());
    assertEquals(1, courseMeetingDto.getId().getPeriod());
    assertEquals(course.getDescription(), courseMeetingDto.getCourse().getDescription());
    s.createCriteria(Student.class).add(Restrictions.like("name", "Gavin", MatchMode.START)).addOrder(Order.asc("name")).createCriteria("enrolments", "e").addOrder(Order.desc("year")).addOrder(Order.desc("semester")).createCriteria("course", "c").addOrder(Order.asc("description")).setProjection(Projections.projectionList().add(Property.forName("this.name")).add(Property.forName("e.year")).add(Property.forName("e.semester")).add(Property.forName("c.courseCode")).add(Property.forName("c.description"))).uniqueResult();
    Projection p1 = Projections.projectionList().add(Property.forName("studentNumber").count()).add(Property.forName("studentNumber").max()).add(Projections.rowCount());
    Projection p2 = Projections.projectionList().add(Property.forName("studentNumber").min()).add(Property.forName("studentNumber").avg()).add(Projections.sqlProjection("1 as constOne, count(*) as countStar", new String[] { "constOne", "countStar" }, new Type[] { StandardBasicTypes.INTEGER, StandardBasicTypes.INTEGER }));
    Object[] array = (Object[]) s.createCriteria(Enrolment.class).setProjection(Projections.projectionList().add(p1).add(p2)).uniqueResult();
    assertEquals(array.length, 7);
    List list = s.createCriteria(Enrolment.class).createAlias("student", "st").createAlias("course", "co").setProjection(Projections.projectionList().add(Property.forName("co.courseCode").group()).add(Property.forName("st.studentNumber").count().setDistinct()).add(Property.forName("year").group())).list();
    assertEquals(list.size(), 2);
    list = s.createCriteria(Enrolment.class).createAlias("student", "st").createAlias("course", "co").setProjection(Projections.projectionList().add(Property.forName("co.courseCode").group().as("courseCode")).add(Property.forName("st.studentNumber").count().setDistinct().as("studentNumber")).add(Property.forName("year").group())).addOrder(Order.asc("courseCode")).addOrder(Order.asc("studentNumber")).list();
    assertEquals(list.size(), 2);
    list = s.createCriteria(Enrolment.class).createAlias("student", "st").createAlias("course", "co").setProjection(Projections.projectionList().add(Property.forName("co.courseCode").group().as("cCode")).add(Property.forName("st.studentNumber").count().setDistinct().as("stNumber")).add(Property.forName("year").group())).addOrder(Order.asc("cCode")).addOrder(Order.asc("stNumber")).list();
    assertEquals(list.size(), 2);
    s.delete(gavin);
    s.delete(xam);
    s.delete(course);
    t.commit();
    s.close();
}
Also used : Projection(org.hibernate.criterion.Projection) Type(org.hibernate.type.Type) Transaction(org.hibernate.Transaction) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) Session(org.hibernate.Session) Test(org.junit.Test)

Aggregations

Projection (org.hibernate.criterion.Projection)4 Type (org.hibernate.type.Type)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 HibernateException (org.hibernate.HibernateException)2 Session (org.hibernate.Session)2 Transaction (org.hibernate.Transaction)2 EnhancedProjection (org.hibernate.criterion.EnhancedProjection)2 Test (org.junit.Test)2 Iterator (java.util.Iterator)1 QueryException (org.hibernate.QueryException)1 JoinType (org.hibernate.sql.JoinType)1 AssociationType (org.hibernate.type.AssociationType)1 CollectionType (org.hibernate.type.CollectionType)1 StringRepresentableType (org.hibernate.type.StringRepresentableType)1