0

I have the following entity:

import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.index.Indexed
import org.springframework.data.mongodb.core.mapping.Document
import javax.validation.constraints.NotNull

@Document
class Book(
    @Id
    var id: Int,
    @Indexed(unique=true)
    @NotNull
    var name: String,
    @NotNull
    var price: Double,
)

and its corresponding Controller with a post method:


import org.springframework.validation.annotation.Validated
import javax.validation.Valid

@RestController
@RequestMapping("/api")
class BookController(val bookRepository: BookRepository) {

    @PostMapping("/books")
    fun postMovie(@Valid @RequestBody book: Book): ResponseEntity<Int> {
        val currentBookEntry = bookRepository.save(book)

        return ResponseEntity.status(HttpStatus.CREATED).body(currentBookEntry.id)
    }
}

I want to return an HTTP 400 response every time when the request body for post is missing a field. For example: In swagger I'm making a post request with the following body:

{
  "name": "Random Book"
}

Since the price is missing, the request should fail. But I'm getting an HTTP 201 response. How can I check if the JSON payload has all the fields completed because neither of @NotNull and @Valid annotations doesn't seem to work.

  • I would help if you included the imports to know what namespace the attribute @NotNull belongs with. – barrypicker Dec 03 '21 at 22:12
  • My bad, I've edited my previous post. @NotNull belongs to javax.validation.constraints – Altair RuS Dec 03 '21 at 22:55
  • 1
    Is this a duplicate of this post? https://stackoverflow.com/questions/42292359/spring-data-mongodb-not-null-annotation-like-spring-data-jpa – barrypicker Dec 03 '21 at 23:10
  • I saw that post, but the solution doesn't seem to work. For example if I make a request whose body has only price in it ``` { "price": 50.5 } ``` I do get an HTTP 400. But if the request looks like this: ``` { "name": "Random Book" } ``` price is automatically assigned with the value 0.0 and the request happens successfully. – Altair RuS Dec 04 '21 at 22:19

0 Answers0