Did you know that you can join database tables into a Java Stream with Java 14’s preview record feature? Read this short article and find out how it is done using the Speedment Stream ORM. We will start with how to set up your project.
Make sure that you have the latest version of your ide (e.g. IDEA 2010.1) that supports the new Java 14 features.
Speedment allows dynamically JOIN:ed database tables to be consumed as standard Java Streams. In this article, we will use the exemplary Sakila database that contains films, actors, languages etc. Download Sakila
here or grab a Docker version here.
Tables, views and joins can easily be turned into standard Java streams with Speedment. This is how it can look like in Java 14:
This will produce the following output:
from() method takes the first table we want to use (
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 entities where the column
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.
Note how the constructor of the
record FilmLanguage is provided in the
build() method. Note also how a film and language entity can be obtained from the record (e.g.
filmLanguage.film()). This is a big improvement over previous Java version where we had to provide rather lengthy custom classes or use tuples with accessor like
get1() rather than the much more descriptive
JOIN Types and Conditions
We can use
crossJoin() and tables can be joined using the conditions
Published on Java Code Geeks with permission by Per Minborg, partner at our JCG program. See the original article here: Java14: Join Database Tables with Java 14’s new Record
Opinions expressed by Java Code Geeks contributors are their own.