R2DBC maps to do relationships between tables in a database

946 views Asked by At

How to use maps in spring data R2DBC, to take map tables/entities with relationships received/sent to a database? Using r2dbcCustomConversions, @WritingConverter and @ReadingConverter. Someone could give.some.example? Thanks a lot

1

There are 1 answers

1
Zinc On

Maybe lc-spring-data-r2dbc can help you, it supports loading and saving entities with relationships.

For example you can declare links like that:

@Table
public class TableWithForeignKey {
  ...
  @ForeignKey(optional = false)
  private LinkedTable myLink;
  ...
}

@Table
public class LinkedTable {
  ...
  @ForeignTable(joinkey = "myLink")
  private List<TableWithForeignKey> links;
  ...
}

When you want the links to be mapped, you can use either lazy loading or select with join.

If you use the methods findBy... (findById, findAll...) of the Spring repository, only the table of the repository will be loaded. In this case, you can use lazy loading. For that you need to declare a methods, with default body, and your method will be automatically implemented:

  public Flux<TableWithForeignKey> lazyGetLinks() {
    return null; // will be implemented
  }

Another way is to make joins directly in the request. There is currently no support to automatically do joins in a repository (like @EntitiGraph in JPA), but you can implement your methods like this:

public interface MyRepository extends LcR2dbcRepository<LinkedTable, Long> {
  
  default Flux<LinkedTable> findAllAndJoin() {
    SelectQuery.from(LinkedTable.class, "root") // SELECT FROM LinkedTable AS root
      .join("root", "links", "link")            // JOIN root.links AS link
      .execute(getLcClient());                  // execute the select and map entities
  }

}

The result will be all LinkedTable instances, with the list of links loaded together from the database.