What’s New in Spring Data (Klara Dan von) Neumann

Translation of the article was prepared on the eve of the start of the course “Spring Framework Developer”

More information about the course can be found by looking open house record


Spring data neumann Is the first release since the transition to a new six-month release cycle. Reducing the time between releases will allow us to release new features more often, and this, in turn, will speed up you too. In this release, in addition to new functionality, there are also important changes that potentially break compatibility with previous versions.

Changing major versions

For the projects listed below, the major version number has been increased due to changes that break compatibility in public APIs or drivers:

  • Spring Data JDBC 2.0 (previous version 1.1)
  • Migration from 1.1 to 2.0 is described in this post
  • Spring Data MongoDB 3.0 (previous version 2.2)
  • Spring Data for Apache Cassandra 3.0 (previous version 2.2)
  • Spring Data Couchbase 4.0 (previous version 3.2)
  • Spring Data Elasticsearch 4.0 (previous version 3.2)
  • For more details on the changes see this post

Before moving on to describing the new functionality, let’s take a look at the changes in the API. For details, see the Upgrading sections in the documentation for the respective modules.

If you’re not ready to update now, keep in mind that the previous Moore release will be supported for another twelve months.

JDBC

Each SQL storage has its own characteristics that require a special approach. To improve their support, changes were made that affected the increase in the major version. Now AbstractJdbcConfiguration by default tries to determine Dialect database from a given DataSource or registered DialectResolver… By default, the JDBC module comes with dialects for H2, HSQLDB, MySQL, Postgres, MariaDB, Microsoft SqlServer, and DB2. Spring Data JDBC now escapes all table and column names by default. Although this may cause you to change your CREATE TABLE or annotations @Column, this will give you more flexibility when naming objects.

MongoDB

The single jar with drivers for MongoDB (mongo-java-driver) is split into several: -sync and -reactivestreams, which allows you to select only the driver you need. That is, both the synchronous and reactive MongoDB drivers are now optional dependencies that must be added manually. When migrating to new drivers, some of the already deprecated APIs were permanently removed, which affected configuration classes such as AbstractMongoConfiguration and XML namespaces provided by Spring Data. For more details see the section to update in the documentation.

Apache Cassandra

The long overdue update of Apache Cassandra drivers to 4.0 not only updates the package and data structure, but also changes behavior in the cluster and in session handling. This led to major configuration changes that affect XML configuration and may affect configuration in code for some complex scenarios (harder than a simple default AbstractCassandraConfiguration).

Couchbase

Following the Couchbase SDK, we upgraded from version 3.x to 4.x, which added automatic index management and transaction support. Read more in Couchbase blog

Elasticsearch

Added support for HTTP Client API, SSL and Proxy. A number of changes were also made, including optimization and removal of the deprecated API, which influenced the change in the major version number. Elasticsearch module now includes Document, which includes Get-, Index- and Search-Requests, which allows using such types as SearchHit, SearchHits and SearchPage

Now let’s move on to innovations.

Repositories with support for Kotlin coroutines

Neumann release continues to develop support Kotlin coroutinestarted in the previous release Mooreby adding their support in the repositories.

Coroutines are maintained through reactive Spring Data repositories. Now you can use reactive query methods or write your own suspended functions.

interface StudentRepository : CoroutineCrudRepository {
    suspend fun findOne(id: String): User
    fun findByLastname(firstname: String): Flow
}

@Primary-repositories and the “search” keyword

These two small changes improve retrieval of repository beans and naming of query methods. Now the annotation @Primary on the interface repositories, it is taken into account in the bean configuration, which helps the container resolve dependencies. Query methods can now be prefixed "search", similarly "find"… That is, now you can write methods "search...By...", eg, searchByFirstname

Even though this was done for databases like Elasticsearch, let’s move on and see how search...By... can be used in Spring Data R2DBC.

Generating R2DBC Queries

So far, Spring Data R2DBC has used the annotation for query methods @Query excluding the default methods provided via interfaces *.Repository… Now generating requests by method name works similarly to other modules:

interface StudentRepository extends ReactiveCrudRepository {

	Flux searchByLastname(String lastname); (1)
}

This is equivalent to:

@Query("select id, firstname, lastname from customer c where c.lastname = :lastname")

Pagination and Query Generation for JDBC

Spring Data JDBC 2.0 supports even more relational databases. We are now running our integration tests on H2, HSQLDB, MySQL, MariaDB, PostgreSQL and DB2.

For these databases, we support query generation and pagination. For example:

interface StudentRepository extends PagingAndSortingRepository {

	Page findByLastname(String lastname);
}

In this release, we also continue to move towards NoSQL, starting with MongoDB and a new way of modifying documents.

MongoDB Update Aggregations

This important change (which was not fully prepared in the Moore release) allows the use of Aggregation Pipeline to update data. Thus, changes can contain complex expressions such as conditions on field values, for example:

AggregationUpdate update = Aggregation.newUpdate()
    .set("average").toValue(ArithmeticOperators.valueOf("tests").avg())
    .set("grade").toValue(ConditionalOperators.switchCases(
        when(valueOf("average").greaterThanEqualToValue(90)).then("A"),
        when(valueOf("average").greaterThanEqualToValue(80)).then("B"),
        when(valueOf("average").greaterThanEqualToValue(70)).then("C"),
        when(valueOf("average").greaterThanEqualToValue(60)).then("D"))
        .defaultTo("F")
    );

template.update(Student.class)
    .apply(update)
    .all();

Also, Spring Data MongoDB will undoubtedly benefit from the recently added support for embedded objects in other modules.

Support for embedded types in Apache Cassandra

Apache Cassandra now supports embedded type mapping, which have long been available in Spring Data JDBC… In the domain model, built-in objects are used for Value Objects whose properties are stored in a single table. In the following example above the field Student.name worth annotation @Embedded, which leads to the fact that all fields of the class Name will be stored in a table Studentconsisting of three columns (student_id, firstname and lastname):

public class Student {

    @PrimaryKey("student_id")
    private String studentId;

    @Embedded(onEmpty = USE_NULL)
    Name name;
}

public class Name {
    private String firstname;
    private String lastname;
}

Elasticsearch audit

Since ElasticSearch has id is not a sufficient criterion for determining whether an object is new, necessary in implementation Persistable provide additional information using the method isNew():

@Document(indexName = "person")
public class Person implements Persistable {

    @Id private Long id;
    private String lastName;
    private String firstName;

    @Field(type = Date)
    private Instant createdDate;
    private String createdBy

    @Field(type = Date)
    private Instant lastModifiedDate;
    private String lastModifiedBy;

    @Override
    public boolean isNew() {
        return id == null || (createdDate == null && createdBy == null);
    }
}

After that adding @EnableElasticsearchAuditing in the configuration registers all the components required for auditing.

Neo4j

Spring Data Neo4j now supports Neo4j 4.0 query syntax with parameters. The placeholder syntax was previously deprecated and has now been completely removed. The module now relies on the latest Neo4j-OGM and Neo4j Java drivers to improve interoperability with the latest Neo4j.

There is also active work on supporting reactivity for graph databases and integrating it into Spring Data with Neo4j RX (although not included in the current release, it is already ready for inclusion in the next).

Apache Geode / VMware Tanzu GemFire

Spring Data Modules for Apache Geode and VMware Tanzu GemFire ​​(spring-data-geode and spring-data-gemfire) are combined into one project under the general name SDG. Apache Geode has been updated to 1.12.0 and GemFire ​​to 9.10.0, which in turn is based on Apache Geode 1.12. In addition, the SDG compiles and runs on JDK versions 8 through 14.

SDG now supports publication of autotransaction eventswhich converts the Cache TransactionEvent from the GemFire ​​/ Geode Cache to the appropriate ApplicationEvent in the context.

You can also now pause sending events on AEQ configured with SDG. Also, when building GemFire ​​/ Geode Locator based apps using SDG annotation @LocatorApplication can be customized Locator to connect to other Locatorthus creating a highly available and resilient cluster.


Learn more about the course.


Read more

  • Spring Boot – OAuth2 and JWT
  • Introduction to Spring Boot Actuator Baeldung
  • Design patterns used in the Spring Framework

Similar Posts

Leave a Reply Cancel reply