Java8 USES the method of querying a database in a streaming manner

  • 2020-04-01 04:36:48
  • OfStack

Because of the differences between relational database operation languages and object-oriented languages, we still spend a lot of time building Bridges between databases and Java applications. Typically, we can write our own mapping layer or use a third-party ORM (Object Relational Mapper) object-relational mapping framework, such as Hibernate. Although ORM frameworks are easy to use, it is not easy to configure and improve the performance of database operations by ORM frameworks. ORM frameworks tend to degrade the performance of our applications. I recently contributed to a new open source project, Speedment, which makes it faster and more efficient to develop database applications using Java 8.

Speedment is an option for working with the database in ORM mode. Whereas previously we needed 100 lines of Java code to work with the database, in Java 8 we might only need one line of code.

In the late 1990s, when I was developing database applications using Java, a lot of the code logic had to be written by myself, such as catching exceptions, type conversions, and so on.

Because of the differences between relational database operation languages and object-oriented languages, we still spend a lot of time building Bridges between databases and Java applications. Typically, we can write our own mapping layer or use a third-party ORM (Object Relational Mapper) object-relational mapping framework, such as Hibernate. Although ORM frameworks are easy to use, it is not easy to configure and improve the performance of database operations by ORM frameworks. ORM frameworks tend to degrade the performance of our applications.

I recently contributed to a new open source project, Speedment, which makes it faster and more efficient to develop database applications using Java 8.

What is Speedment?

Speedment is an open source project that is a new Java library based on the new features of Java 8. Since the beginning of this project, its code has been written entirely in Java 8. Speedment queries the database using standard streams, which eliminates the need for developers to learn any new query apis and to consider JDBC, ResultSet, and other database-specific operations.

Speedment automatically generates code based on an existing database. Because of the way it works, developers don't need to write a single line of code for database entities. The generated code also contains JavaDocs help documentation, which eliminates the need for developers to write entity classes for objects like User or Book. Instead, we simply create or use an existing database, then connect to it with Speedment, which then analyzes the database structure to generate the entity class code.

More interestingly, Speedment USES a hare as its mascot. In the following example, we will use a database called "hare" to demonstrate the use of Speedment. The table structure of the database is as follows:

Mysql> Explain the hare;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(45) | NO | | NULL | |
| color | varchar(45) | NO | | NULL | |
| age | int(11) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
4 rows in set (0.01 SEC)

Here is a corresponding entity class generated by Speedment based on the database information (JavaDocs is removed here for brevity) :


public interface Hare extends Entity<Hare> {
public final static ReferenceComparableField<Hare, Integer> ID = new ReferenceComparableFieldImpl<>("id", Hare::getId, Hare::setId);
public final static ReferenceComparableStringField<Hare> NAME = new ReferenceComparableStringFieldImpl<>("name", Hare::getName, Hare::setName);
public final static ReferenceComparableStringField<Hare> COLOR = new ReferenceComparableStringFieldImpl<>("color", Hare::getColor, Hare::setColor);
public final static ReferenceComparableField<Hare, Integer> AGE = new ReferenceComparableFieldImpl<>("age", Hare::getAge, Hare::setAge);
Integer getId();
String getName();
String getColor();
Integer getAge();
Hare setId(Integer id);
Hare setName(String name);
Hare setColor(String color);
Hare setAge(Integer age);

Stream<Carrot> findCarrotsByOwner();
Stream<Carrot> findCarrotsByRival();
Stream<Carrot> findCarrots();
}

I'll cover the use of the find*() method in a separate article, which can be used instead of SQL joins operations.

Queries example

The following example shows how to query the database information of the Hare table:

List< Hare> OldHares = hares. Stream ()
Filter (AGE. GreaterThan (8))
Collect (toList ());

Intelligent flow

The code above looks like it has traversed all the rows of the hare database table, but it doesn't. Stream is intelligent. When it arrives at the collect() operation, it will analyze the filter operation and infer that the hare. Age is greater than 8. 8 "operation same effect. If you use multiple filters, they will be combined to save the flow. Here's another example of doing multiple operations in a streaming fashion:

Long noOldHares = hares. Stream ()
Filter (AGE. GreaterThan (8))
. MapToInt (Hare: : getAge)
The sorted ()
The count ();

In the above code, when the stream reaches the count() operation, it checks its own pipe. First, the AGE operation in the above example is inferred, and then, without changing the count() result, the mapToInt() and sorted() operations are inferred, which can be eliminated, so the operation in this code is saved to "select count(*) from hare where AGE > 8 ". This means that you can use Java 8 streams without having to worry so much about how the stream is converted to SQL.

How to download and join us

If you want to learn how to use the Speedment API and how to use Speedment in your project, you can visit www.speedment.org, comment on gitter, or download the Speedment source code from GitHub to contribute your own code.

conclusion

Going back to some of the earlier projects, a database class with more than 100 lines of code can now be reduced to 1 line of code using Java 8. That's Moore's law reversed, and in 14 years (= 7 mole cycles), the number of rows has roughly halved by seven. That's progress!

What is a data stream

Streams represent objects from sequences that support aggregation operations. The following are the characteristics of the data flow.

Element sequence - a stream provides a set of sequential elements of a specific type. The stream captures/computes the elements of the requirement. It does not store elements.

Source - streams use collections, arrays, or I/O resources as input sources.

Aggregation operations - data flow supports aggregation operations such as filter, map, limit, reduced, find, and match.

Piped transport - the return flow of most stream operations is itself such that their results can be piped. These operations are called intermediate operations and their function is to take the input and process the input and output back to the target. The collect() method is a terminal operation, which typically occurs at the end of a pipeline transport operation to mark the end of a stream.

The automatic iteration-flow operation is internally iterated, where the explicit iteration requires the collection to provide the source elements.


Related articles: