21
1 / 21 Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University Database Programming Chapter 8. Criteria Queries Simple Criteria Compunding Criteria Querying by Example

Chapter 8. Criteria Querieselearning.kocw.net/KOCW/document/2016/hanbat/kimyoungchan/9.pdf · [java] Track: "Video Killed the Radio Star" (The Buggles) 00:03:49, from VHS Videocassette

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

1 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Chapter 8. Criteria Queries

Simple Criteria

Compunding Criteria

Querying by Example

2 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Criteria Queries

Relational Query Languages (HQL and SQL)

– are extremely flexible and powerful,

– but take a long time to truly master.

– also be awkward to mix a query language's syntax with Java code.

Criteria Queries

– provide a way to create and connect simple Java objectsthat act as filters for picking your desired results.

– also allows you to supply example objects to show what you're looking for,with control over which details matter and which properties to ignore.

– To be fair, has its own disadvantages.

• Expanding long query expressions into a Java API makes them take up more room.

• They'll be less familiar to experienced database developers than a SQL-like query.

3 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Using Simple Criteria …

Example 8-1. The beginnings of a criteria query

– building a criteria query to find all tracks.

QueryTest.java :

public static List tracksNoLongerThan(Time length, Session session) {

Criteria criteria = session.createCriteria(Track.class);

return criteria.list();

}

% ant qtest...qtest:

[java] Track: "Russian Trance" (PPK) 00:03:30, from Compact Disc[java] Track: "Video Killed the Radio Star" (The Buggles) 00:03:49, from VHS Videocassette tape[java] Track: "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc[java] Track: "Adagio for Strings (Ferry Corsten Remix)" (Ferry Corsten, William Orbit, Samuel

Barber) 00:06:35, from Compact Disc[java] Track: "Adagio for Strings (ATB Remix)" (William Orbit, ATB, Samuel Barber) 00:07:39, from

Compact Disc[java] Track: "The World '99" (Ferry Corsten, Pulp Victim) 00:07:05, from Digital Audio Stream[java] Track: "Test Tone 1" 00:00:10[java] Comment: Pink noise to test equalization

4 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Using Simple Criteria …

Example 8-3. Criteria query (that fully replaces the HQL version from Chapter 3)

– building a criteria query to find tracks shorter than a specified length (seven minutes).

QueryTest.java :

public static List tracksNoLongerThan(Time length, Session session) {

Criteria criteria = session.createCriteria(Track.class);

criteria.add(Restrictions.le("playTime", length));

return criteria.list();

}

public static List tracksNoLongerThan(Time length, Session session) {

return session.createCriteria(Track.class).add(Restrictions.le("playTime", length)).list();

}

5 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Using Simple Criteria …

Example 8-4. Results of our complete simple criteria query

% ant qtest

qtest:

[java] Track: "Russian Trance" (PPK) 00:03:30, from Compact Disc

[java] Track: "Video Killed the Radio Star" (The Buggles) 00:03:49, from VHS Videocassette tape

[java] Track: "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc

[java] Track: "Adagio for Strings (Ferry Corsten Remix)" (Ferry Corsten, Samuel Barber, William

Orbit) 00:06:35, from Compact Disc

[java] Track: "Test Tone 1" 00:00:10

[java] Comment: Pink noise to test equalization

6 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Using Simple Criteria …

Sorting the list of results

– addOrder( )

Retrieving a subset of all matching objects

– setMaxResults( )

– setFristResult( )

– a variety of other scrolling and manipulation methods

Example 8-6. Sorting the results by title

– Order { asc( ), desc( ), ignoreCase( ) }

public static List tracksNoLongerThan(Time length, Session session) {

Criteria criteria = session.createCriteria(Track.class);

criteria.add(Restrictions.le("playTime", length));

criteria.addOrder(Order.asc("title").ignoreCase());

return criteria.list();

}

7 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Using Simple Criteria

Example 8-7. The sorted results

% gradle qtest

qtest:

[java] Track: "Adagio for Strings (Ferry Corsten Remix)" (Ferry Corsten, Samuel Barber, William

Orbit) 00:06:35, from Compact Disc

[java] Track: "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc

[java] Track: "Russian Trance" (PPK) 00:03:30, from Compact Disc

[java] Track: "Test Tone 1" 00:00:10

[java] Comment: Pink noise to test equalization

[java] Track: "Video Killed the Radio Star" (The Buggles) 00:03:49, from VHS Videocassette tape

8 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Compounding Criteria …

You can add more than one Criterion to your query,and all of them must be satisfied for objects to be included in the results.

– This is equivalent to building a compound criterion using Restrictions.conjunction( ), described in Appendix B.

Example 8-8. A pickier list of short tracks

Example 8-9. Tracks of seven minutes or less containing a capital "A" in their titles

Criteria criteria = session.createCriteria(Track.class);

criteria.add(Restrictions.le("playTime", length));

criteria.add(Restrictions.like("title", "%A%"));

criteria.addOrder(Order.asc("title").ignoreCase());

return criteria.list();

qtest:

[java] Track: "Adagio for Strings (Ferry Corsten Remix)" (Samuel Barber, Ferry Corsten,

William Orbit) 00:06:35, from Compact Disc

[java] Track: "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc

9 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Compounding Criteria …

Hibernate Matching

– Restrictions.like("title", "%A%") // SQL “%” syntax

– Restrictions.like("title", "A", MatchMode.ANYWHERE)

– Restrictions.ilike( ) // case-insensitive matching

If you want to find any objects matching any one of your criteria, rather than requiring them to fit all criteria

– Restrictions.disjunction( ) // OR.add(Restrictions.like("title", “%A%")).add(Restrictions.le("playTime", "00:07:00"))

– Restrictions.or( criterionA, criterionB)

– Restrictions.conjunction( ) // AND.add(Restrictions.like("title", "%A%")).add(Restrictions.le("playTime", "00:07:00"))

– Restrictions.and(criterionA, criterionB)

10 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Compounding Criteria …

Example 8-10. Picking tracks more leniently

Example 8-11. Tracks whose title contains the letter "A," or whose length is seven minutes or less

Criteria criteria = session.createCriteria(Track.class);

Disjunction any = Restrictions.disjunction();

any.add(Restrictions.le("playTime", length));

any.add(Restrictions.like("title", "%A%"));

criteria.add(any);

criteria.addOrder(Order.asc("title").ignoreCase());

return criteria.list();

qtest:[java] Track: "Adagio for Strings (ATB Remix)" (ATB, William Orbit, SamuelBarber) 00:07:39, from Compact Disc[java] Track: "Adagio for Strings (Ferry Corsten Remix)" (Ferry Corsten, William Orbit, Samuel Barber) 00:06:35,

from Compact Disc[java] Track: "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc[java] Track: "Russian Trance" (PPK) 00:03:30, from Compact Disc[java] Track: "Test Tone 1" 00:00:10[java] Comment: Pink noise to test equalization[java] Track: "Video Killed the Radio Star" (The Buggles) 00:03:49, from VHS Videocassette Tape

11 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Compounding Criteria

Restrictions.disjunction() vs Restrictions.or()

Criteria criteria = session.createCriteria(Track.class);

criteria.add( Restrictions.disjunction()

.add(Restrictions.le("playTime", length))

.add(Restrictions.like("title", "%A%"))

);

criteria.addOrder(Order.asc("title").ignoreCase());

return criteria.list();

Criteria criteria = session.createCriteria(Track.class);

criteria.add( Restrictions.or( Restrictions.le("playTime", length),

Restrictions.like("title", "%A%") )

);

criteria.addOrder(Order.asc("title").ignoreCase());

return criteria.list();

12 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Projection and Aggregation with Criteria …

Example 8-13. Simple projection on a single property

/*** Retrieve the titles of any tracks that contain a particular text string.** @param text the text to be matched, ignoring case, anywhere in the title.* @param session the Hibernate session that can retrieve data.* @return the matching titles, as strings.*/

public static List titlesContainingText(String text, Session session) {

Criteria criteria = session.createCriteria(Track.class);

criteria.add(Restrictions.like("title", text, MatchMode.ANYWHERE). ignoreCase());

criteria.setProjection(Projections.property("title"));

return criteria.list();

}

QueryTest.java:

System.out.println(titlesContainingText("v", session));

qtest:

[java] [Video Killed the Radio Star, Gravity's Angel]

13 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Projection and Aggregation with Criteria …

Example 8-14. Projection on two properties

/*** Retrieve the titles and play times of any tracks that contain a* particular text string.* * @param text the text to be matched, ignoring case, anywhere in the title.* @param session the Hibernate session that can retrieve data.* @return the matching titles and times wrapped in object arrays.*/public static List titlesContainingTextWithPlayTimes(String text, Session session) {

Criteria criteria = session.createCriteria(Track.class);criteria.add(Restrictions.like("title", text, MatchMode.ANYWHERE).ignoreCase());criteria.setProjection(Projections.projectionList().

add(Projections.property("title")). add(Projections.property("playTime")));

return criteria.list();}

QueryTest.java:

for (Object o : titlesContainingTextWithPlayTimes("v", session)) {Object[] array = (Object[])o;System.out.println("Title: " + array[0] + " (Play Time: " + array[1] + ')');

}

qtest:[java] Title: Video Killed the Radio Star (Play Time: 00:03:49)[java] Title: Gravity's Angel (Play Time: 00:06:06)

14 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Projection and Aggregation with Criteria …

Example 8-15. Projection with aggregation

/*** Print statistics about various media types. */public static void printMediaStatistics(Session session) {

Criteria criteria = session.createCriteria(Track.class);criteria.setProjection(Projections.projectionList().

add(Projections.groupProperty("sourceMedia")). add(Projections.rowCount()). add(Projections.max("playTime")));

for (Object o : criteria.list()) { Object[] array = (Object[])o;System.out.println(array[0] + " track count: " + array[1] + "; max play time: " + array[2]);

}}

QueryTest.java:

printMediaStatistics(session);

qtest:[java] CD track count: 4; max play time: 00:07:39[java] VHS track count: 1; max play time: 00:03:49[java] STREAM track count: 1; max play time: 00:07:05[java] null track count: 1; max play time: 00:00:10

15 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Projection and Aggregation with Criteria

Sorting on Projection with aggregation

/*** Print statistics about various media types. */public static void printMediaStatistics(Session session) {

Criteria criteria = session.createCriteria(Track.class);criteria.setProjection(Projections.projectionList().

add(Projections.groupProperty("sourceMedia"). as("media")). // aliasesadd(Projections.rowCount()). add(Projections.max("playTime")));

criteria.addOrder(Order.asc("media")); // sorting

for (Object o : criteria.list()) { Object[] array = (Object[])o;System.out.println(array[0] + " track count: " + array[1] + "; max play time: " + array[2]);

}}

QueryTest.java:

printMediaStatistics(session);

qtest:[java] null track count: 1; max play time: 00:00:10[java] CD track count: 4; max play time: 00:07:39[java] STREAM track count: 1; max play time: 00:07:05[java] VHS track count: 1; max play time: 00:03:49

16 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Applying Criteria to Associations …

Example 8-16. Filtering tracks based on their artist associations

/*** Retrieve any tracks associated with artists whose name matches a SQL string pattern.* */public static List tracksWithArtistLike(String namePattern, Session session){

Criteria criteria = session.createCriteria(Track.class);Criteria artistCriteria = criteria.createCriteria("artists"); artistCriteria.add(Restrictions.like("name", namePattern)); artistCriteria.addOrder(Order.asc("name").ignoreCase()); return criteria.list();

}

QueryTest.java:...// Ask for a session using the JDBC information we've configuredSession session = sessionFactory.openSession();try {

// Print tracks associated with an artist whose name ends with "n"List tracks = tracksWithArtistLike("%n", session);for (ListIterator iter = tracks.listIterator() ;

...

qtest:[java] Track: "The World '99" (Pulp Victim, Ferry

Corsten) 00:07:05, from Digital Audio Stream[java] Track: "Adagio for Strings (Ferry Corsten Remix)"

(William Orbit, Samuel Barber, Ferry Corsten) 00:06:35, from Compact Disc

[java] Track: "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc

17 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Applying Criteria to Associations

Equivalent of SQL’s “select distinct”

– criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)

18 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Querying by Example …

Example 8-19. Using an example entity to populate a criteria query

/*** Retrieve any tracks that were obtained from a particular source media type.*/public static List tracksFromMedia(SourceMedia media, Session session) {

Track track = new Track(); track.setSourceMedia(media);Example example = Example.create(track);

Criteria criteria = session.createCriteria(Track.class); criteria.add(example);criteria.addOrder(Order.asc("title"));return criteria.list();

}

QueryTest.java:...// Ask for a session using the JDBC information we've configuredSession session = sessionFactory.openSession();try {

// Print tracks that came from CDsList tracks = tracksFromMedia(SourceMedia.CD, session);for (ListIterator iter = tracks.listIterator() ;

...

qtest:[java] Track: "Adagio for Strings (ATB Remix)" (ATB, Samuel

Barber, William Orbit) 00:07:39, from Compact Disc[java] Track: "Adagio for Strings (Ferry Corsten Remix)"

(Samuel Barber, William Orbit, Ferry Corsten) 00:06:35, from Compact Disc

[java] Track: "Gravity's Angel" (Laurie Anderson) 00:06:06, from Compact Disc

[java] Track: "Russian Trance" (PPK) 00:03:30, from Compact Disc

19 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Querying by Example

Example 8-16. Filtering tracks based on their artist associations

public static List tracksWithArtistLike(String namePattern, Session session){

Criteria criteria = session.createCriteria(Track.class);Criteria artistCriteria = criteria.createCriteria("artists"); artistCriteria.add(Restrictions.like("name", namePattern)); artistCriteria.addOrder(Order.asc("name").ignoreCase()); return criteria.list();

}

public static List tracksWithArtistLike(String namePattern, Session session){

Criteria criteria = session.createCriteria(Track.class);Example example = Example.create(new Artist(namePattern, null, null));criteria.createCriteria("artists")

.add(example.enableLike())

.addOrder(Order.asc("name").ignoreCase( ) );return criteria.list();

}

20 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Property-Oriented Criteria Factories …

Property is another factory for criteria, much like Restrictions.

Example 8-19. Using an example entity to populate a criteria query

– Ordering

– Projection

criteria.addOrder(Order.asc("name").ignoreCase());

criteria.addOrder(Property.forName("name").asc().ignoreCase());

criteria.setProjection(Projections.max("playTime"));

criteria.setProjection(Property.forName("playTime").max());

21 / 21Prof. Youngchan KIM, Dept of Computer Engineering, Hanbat National University

Database Programming

Materials for Further Study

Hibernate Home

– http://www.hibernate.org/

Hibernate Manual

– Hibernate Getting Started Guide 3.6

• http://docs.jboss.org/hibernate/core/3.6/quickstart/en-US/html/

– Hibernate Reference Documentation 3.6

• http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/

• http://docs.jboss.org/hibernate/core/3.6/reference/en-US/pdf/hibernate_reference.pdf

– Hibernate Reference Documentation 4.3 and 5.0

Hibernate Tutorial

– http://www.mkyong.com/tutorials/hibernate-tutorials/