Learn how to use standard Java streams which automatically convert themselves to Hibernate/JPA Queries.
A large proportion of Java database applications are using Hibernate/JPA to bridge the gap between Java and SQL. Until recently, we were forced to mix Java and JPQL or to use complex imperative criteria builders to create database queries. Both of these methods are inherently neither type-safe nor very intuitive. The newly launched open-source library JPAstreamer addresses these issues by allowing you to express Hibernate/JPA queries using Java Streams. This means we can avoid any impedance mismatches between JPQL/HQL and Java and get full type-safety. In this article, I will show you how to put Java Stream queries to work in your application using JPAstreamer.
As mentioned, JPAstreamer allows JPA queries to be expressed as standard Java Streams using short and concise, type-safe declarative constructs. This makes our code shorter, less complex, and easier to read and maintain. Best of all, we can stick to using only Java code without needing to mix it with SQL/JPQL or other language constructs/DSL.
In short, we can query a database like this:
jpaStreamer.stream(Film.class) .sorted(Film$.length.reversed()) .limit(15) .map(Film$.title) .forEach(System.out::println);
This prints the title of the 15 longest films in the database.
JPAstreamer is using the same license as Hibernate (LGPL). This makes it easy to use in existing Hibernate projects. JPAstreamer also works with other JPA providers such as EclipseLink, OpenJPA, TopLink etc.
Installing JPAstreamer entails just adding a single dependency in your Maven/Gradle configuration file as described here. For example, Maven users add the following dependency:
<dependency> <groupId>com.speedment.jpastreamer</groupId> <artifactId>jpastreamer-core</artifactId> <!-- Make sure to use the latest version --> <version>0.1.8</version> </dependency>
Let's have a look at how JPAstreamer fits in an existing application.
What is OpenJDK? OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE).
This "Java Tutorial for Beginners" Full course will help you master all the major concepts in java such as Arrays, Polymorphism, Abstraction, Inheritance, and Collections.
This Edureka video on “Java IO Streams” will give you a brief insight into various input-output streams used in Java Programming.
In this video we will learn about all the major concepts that come under Java Core . The course is very carefully designed and is made with keeping simplicit...
In this tutorial, we will learn what Streams are in Java by comparing the Stream API to SQL statements as an implementation approach.