Annotation-based query

SqlQuery takes a class and a SQL string. To fetch Eden Hazard's details, we need to construct a SqlQuery object with the following details:

SqlQuery<SoccerPlayerKey, SoccerPlayer> sqlQuery = new SqlQuery<>(SoccerPlayer.class, "name = ?");

The query method of IgniteCache takes a SqlQuery object and returns QueryCursor. The QueryCursor contains a collection of Entry. An Entry represents a key-value pair. So, the SqlQuery can fetch you a collection of key-value pairs. The following code snippet queries the playerCache to return a collection of players where the name="Eden Hazard". It returns a QueryCursor of Entry<SoccerPlayerKey, SoccerPlayer>:

 QueryCursor<Entry<SoccerPlayerKey, SoccerPlayer>> resultCursor = playerCache
.query(sqlQuery.setArgs("Eden Hazard"));

We need to loop through the cursor to print the values. The following code prints the results using the Java 8 lambda function:

resultCursor.forEach(e -> { System.out.println(e.getValue());});

When we run the program, it prints Hazard's details:

How about joining tables? We'll join the player and club tables and fetch details. The following code snippet uses an ANSI-99 SQL join to fetch Barcelona players.  When your SqlQuery fetches data from many tables, you can mention the first table directly, but the following tables need to be accessed by their cache name, such as "cacheName".ClassName:

System.out.println("Find Barcelona players");
sqlQuery = new SqlQuery<>(SoccerPlayer.class, "from SoccerPlayer, "" + CLUB_SQL_CACHE + "".SoccerClub "
+ "where SoccerPlayer.clubId = SoccerClub.id and SoccerClub.name = ?");

resultCursor = playerCache.query(sqlQuery.setArgs("Barcelona"));
resultCursor.forEach(e -> {
System.out.println(e.getValue());
});

The following SQL code is responsible for joining the tables, SoccerPlayer.clubId = SoccerClub.id and SoccerClub.name = ?. It prints the Barcelona players' details:

We fetched the player objects, but what if I'm interested in selecting a specific column, not the entire object? The SqlFieldsQuery API enables querying the fields.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.31.165