Java 11: JOIN Tables, Get Java Streams
Ever wondered how you could turn joined database tables into a Java Stream? Read this short article and find out how it is done using the Speedment Stream ORM. We will start with a Java 8 example and then look into the improvements with Java 11.
Java 8 and JOINs
Speedment allows dynamically JOIN:ed database tables to be consumed as standard Java Streams. We begin by looking at a solution for Java 8 using the Sakila exemplary database:
Speedment app = ...; JoinComponent joinComponent = app.getOrThrow(JoinComponent.class); Join<Tuple2OfNullables<Language, Film>> join = joinComponent .from(LanguageManager.IDENTIFIER) .innerJoinOn(Film.LANGUAGE_ID).equal(Language.LANGUAGE_ID) .build(); join.stream() .forEach(System.out::println);
This will produce the following output (reformatted and shortened for readability):
Tuple2OfNullablesImpl { LanguageImpl { languageId = 1, name = English, ... }, FilmImpl { filmId = 1, title = ACADEMY DINOSAUR, ... } } Tuple2OfNullablesImpl { LanguageImpl { languageId = 1, name = English, ... }, FilmImpl { filmId = 2, title = ACE GOLDFINGER, ... } } Tuple2OfNullablesImpl { LanguageImpl { languageId = 1, name = English, ... }, FilmImpl { filmId = 3, title = ADAPTATION HOLES, ... } } ...
Java 11 and JOINs
In the new Java version 11 there is Local-Variable-Type-Inference (aka var
declaration) which makes it even easier to write joins with Speedment. We do not have to explicitly state the type of the join variable:
Speedment app = ...; JoinComponent joinComponent = app.getOrThrow(JoinComponent.class); var join = joinComponent .from(LanguageManager.IDENTIFIER) .innerJoinOn(Film.LANGUAGE_ID).equal(Language.LANGUAGE_ID) .build(); join.stream() .forEach(System.out::println);
Code Breakdown
Thefrom()
method takes the first table we want to use (Language
). The innerJoinOn()
method takes a specific column of the second table we want to join. Then, the equal()
method takes a column from the first table that we want to use as our join condition. So, in this example, we will get matched Language
and Film
entities where the column Film.LANGUAGE_ID
equal Language.LANGUAGE_ID
.
Finally, build()
will construct our Join
object that can, in turn, be used to create Java Streams. The Join
object can be re-used over and over again.
JOIN Types and Conditions
We can use innerJoinOn()
leftJoinOn()
,rightJoinOn()
and crossJoin()
and tables can be joined using the conditions equal()
, notEqual()
, lessThan()
, lessOrEqual()
, greaterThan()
and lessOrEqual()
.
What’s Next?
Download open-source Java 11 here.
Download Speedment here.
Read all about the JOIN functionality in the Speedment User’s Guide.
Published on Java Code Geeks with permission by Per Minborg, partner at our JCG program. See the original article here: Java 11: JOIN Tables, Get Java Streams Opinions expressed by Java Code Geeks contributors are their own. |