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

The translation of the article was prepared in anticipation of the start of the course "Developer on the Spring Framework" .



You can learn more about the course by looking at the record of the open day .










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 influenced the increase in the major version. Now, AbstractJdbcConfigurationby default, it tries to identify Dialectdatabases from given DataSourceor 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. While this may cause you to change yours CREATE TABLEor annotations @Column, this will give you more flexibility in 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. With the migration to new drivers, some of the already deprecated APIs were permanently removed, affecting configuration classes such as the AbstractMongoConfigurationXML namespaces provided by Spring Data. For details, see the upgrade section 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 has resulted in major configuration changes that affect XML configuration and may affect configuration in code for some complex scenarios (harder than a simple default setting 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 on the 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. The Elasticsearch module now includes Document, which includes Get-, Index-and Search-Requests, which allows you to use types such as SearchHit, SearchHitsand SearchPage.



Now let's move on to innovations.



Repositories with support for Kotlin coroutines



The Neumann release continues to build on the support for Kotlin coroutines that started in the previous Moore release by adding support for them 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<Student, String> {
    suspend fun findOne(id: String): User
    fun findByLastname(firstname: String): Flow<Student>
}


@Primary-repositories and the "search" keyword



These two small changes improve retrieval of repository beans and naming of query methods. Now the annotation @Primaryon the interface repositories is taken into account in the bean configuration, which helps the container resolve dependencies. You can now use a prefix for query methods "search", similarly "find". That is now possible to write methods "search...By...", eg searchByFirstname.



Although this was done for databases like Elasticsearch, let's move on and see how search...By...you can use R2DBC in Spring Data.



Generating R2DBC Queries



So far, Spring Data R2DBC has used annotation @Queryfor query methods, except for the default methods exposed through interfaces *.Repository. Now generating requests by method name works similarly to other modules:



interface StudentRepository extends ReactiveCrudRepository<Student, Long> {

	Flux<Student> 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 instance:



interface StudentRepository extends PagingAndSortingRepository<Student, Long> {

	Page<Student> 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 Aggregation Pipeline to be used 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 has 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, Student.namethere is an annotation above the field @Embedded, which causes all fields of the class to Namebe stored in a table Studentconsisting of three columns ( student_id, firstnameand 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 in ElasticSearch presence is idnot a sufficient criterion for determining whether an object is new, it is necessary to Persistableprovide additional information during implementation using the method isNew():



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

    @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);
    }
}


The addition @EnableElasticsearchAuditingto the configuration then logs 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 this is not included in the current release, it is already ready for inclusion in the next one).



Apache Geode / VMware Tanzu GemFire



Spring Data modules for Apache Geode and VMware Tanzu GemFire ( spring-data-geodeand spring-data-gemfire) are combined into one project under the title 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. The



SDG now supports publishing of autotransaction events , which maps the Cache TransactionEvent from the GemFire ​​/ Geode Cache to the appropriate ApplicationEvent in the context.



It is also now possible to pause sending events on an AEQ configured with SDG. Also, when building GemFire ​​/ Geode Locator based applications using SDG annotation, @LocatorApplicationyou can customizeLocator to connect to other Locators , thus creating a highly available and resilient cluster.






Learn more about the course.






Read more






All Articles