Samiron
Samiron

Reputation: 5317

How to check if exists when using CrudRepository#getOne()

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

Answers (2)

Jens Schauder
Jens Schauder

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

Mohsen Msr
Mohsen Msr

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

Related Questions