Save Short Associations
What is Short Association
A short association refers to only changing the association relationship between the current object and other objects, without further modifying the associated object.
For the UI interface:
-
Reference association (one-to-one and many-to-one) is rendered as a radio menu
-
Collection association (one-to-many and many-to-many) is rendered as a multiple select menu
For example:
Book Form
O'REILLY
Eve Procello, Alex Banks
Define Input DTO
-
Install DTO language Intellij plugin: https://github.com/ClearPlume/jimmer-dto (This process is not required but highly recommended)
-
Create a new directory
src/main/dto
-
Under
src/main/dto
, create a fileBook.dto
and write the following code:Book.dtoinput BookInputWithShortAssociations {
#allScalars(this)
id(store) //default alias storeId
id(authors) as authorIds
}
Generated Code
- Java
- Kotlin
BookInputWithShortAssociations.java
@GeneratedBy(
file = "<yourproject>/src/main/dto/Book.dto"
)
public class BookInputWithShortAssociations implements Input<Book> {
@Nullable
private Long id;
@NotNull
private String name;
private int edition;
@NotNull
private BigDecimal price;
@Nullable
private Long storeId;
@NotNull
private List<Long> authorIds;
...Omit other methods...
}
BookInputWithShortAssociations.kt
@GeneratedBy(
file = "<yourproject>/src/main/dto/Book.dto"
)
data class BookInputWithShortAssociations(
val id: Long?,
val name: String,
val edition: Int,
val price: BigDecimal,
val storeId: Long?
val authorIds: List<Long>
) : Input<Book> {
...Omit other methods...
}
Write HTTP Service
- Java
- Kotlin
BookController.java
@RestController
public class BookController {
private final JSqlClient sqlClient;
public BookController(JSqlClient sqlClient) {
this.sqlClient = sqlClient;
}
@PutMapping("/book")
public int saveBookInputWithShortAssociations(
@RequestBody BookInputWithShortAssociations input
) {
return sqlClient
.save(input)
.getTotalAffectedRowCount();
}
}
BookController.java
class BookController(
private val sqlClient: KSqlClient
) {
@PutMapping("/book")
fun saveBookInputWithShortAssociations(
@RequestBody input: BookInputWithShortAssociations
): Int =
sqlClient
.save(input)
.totalAffectedRowCount
}
It can be seen that no matter how the Input DTO changes, Jimmer still only needs one method call to complete data saving.