Reputation: 5317
I have a Document
entity. To edit a document you must acquire a DocumentLock
.
Request API to edit a document looks like below. edit=true
allows to fetch the record from database with 'FOR UPDATE`.
GET /api/document/123?edit=true
In Back end side, we do like this (of course over simplified),
Document document = documentRepository.getOne(documentId) //<--- (1)
if(document == null){ //<--- (2) This is always false
//Throw exception
}
DocumentLock dl = DocumentLock.builder()
.lockedBy(user)
.lockedAt(NOW)
.document(document)
.build()
documentLockRepository.save(dl);
We are using getOne()
because we do not need to fetch whole document from database, we are just creating a relation with DocumentLock
object.
Question is, how to ensure the document actually exists? Because getOne()
will always return the proxy and I do not see any obvious way to check if the record exists in databse.
Versions:
Update: removed additional questions.
Upvotes: 2
Views: 859
Reputation: 81990
Use findById
or existsById
. Yes they do access the database. That is the point of it, isn't it?
getOne
is explicitly for use cases where you already know the entity exists and only need the id wrapped in something that looks like the entity.
Upvotes: 2
Reputation: 9
If your repository returning value or its transactional management is confusing, you should check your repository codes and entity class design even session configurations that used for querying or even your Datastore design because everything looks fine in this code fragment
Upvotes: 0