Before proceeding with the solution, there are a few things to consider.
- This is a REST API call that requires simplicity in terms of use.
- Server-side code should also consider the performance implications of the chosen implementation.
- The API must be reliable . The point is that what can come, the request should always accept the flows (lucky / exception) conceived in the design.
Based on these considerations, I would suggest the following approach.
- In the DAO, define two different methods:
updateRecord(Long id, String username) and getRecord(Long id) . - Mark the transaction transaction attribute (
@Transaction ) as follows- Mark the transaction attribute for
updateRecord as REQUIRED . - Mark the transaction attribute for
getRecord as NOT_REQUIRED , since this is a pure read access.
- Please note that in all cases, at least a database call is required.
- From the controller, first call the
updateRecord method. This method will return an integer. - If the return value is nonzero, call
getRecord to retrieve the updated record from the database. - If the return value is zero, this means that the user does not exist and you do not need to call
getRecord . Corresponding error response (404 Not Found) to the returned client. - In this approach, you save one database call when the user does not exist.
In general, this approach is neat, less cluttered, and, most importantly, simple and effective (we restrict the transaction boundary only for invoking updates). Moreover, getRecord can be used independently as another API to retrieve a record (without a transaction).
source share