Skip to content
Guillaume Le Cousin edited this page Apr 9, 2022 · 1 revision

Create an entity class

Mapping a database table to an entity class is done by annotating the class:

@Table
public class MyTable {

	@Id
	private Long id;

	@Column
	private String myTextColumn;
	
	public Long getId() {
		return id;
	}
	
	public String getMyTextColumn() {
		return this.myTextColumn;
	}
	
	public void setMyTextColumn(String myTextColumn) {
		this.myTextColumn = myTextColumn;
	}
	
}

In this example, we note that the class is annotated with @Table, the primary key with @Id, and the attribute with @Column. Getters and setters are done as usual (may be done through lombok if you are using it).

Table name and column name

By default, Spring Data R2DBC will convert the class name and attribute name into table name and column name respectively, by converting Camel case into lower case with underscore. In our example the table name will be my_table and the column names will be id and my_text_column.

Advanced usage note : This behavior can be changed by replacing the NamingStrategy given to the LcR2dbcMappingContext, either by overriding the method r2dbcMappingContext in the configuration class (if you are using the provded configuration class) or the method buildMappingContext of class LcR2dbcEntityOperationsBuilder if you are using it.

If you want to specify a custom name, you can just add the name in the annotation:

@Table("book")
public class MyTable {

	@Column("title")
	private String myTextColumn;
	
}

In this example the table name will be book and the column will be title. When using a custom name, SQL queries will be generated with quotes around the name. This ensures the name used is the specified one, but it also allows to use reserved keywords such as "user" or "table" which are not accepted without quotes in most of the databases. (Note: this quoting is specific to this library, Spring Data R2DBC does not use quotes which avoid using reserved keywords).

Access data using a Spring Data Repository

The usual way to make queries with Spring Data is to use repositories. The documentation for Spring Data R2DBC repositories can be found here.

Here is an example:

public interface MyTableRepository extends R2dbcRepository<MyTable, Long> {

	Flux<MyTable> findByMyTextColumn(String myTextColumn);

}

The usual methods such as findById, save, deleteById ... are automatically provided by R2dbcRepository.

Using lc-spring-data-r2dbc, you can use those repositories in exactly the same way, nothing changes here.

Next

Next step is to go deeper into IDs, and see how we can generate primary keys or have tables with several columns as unique key.