2

I am using :

  • spring data rest
  • lombok

When I receive my entity in my controller

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Long create(@RequestBody Blog blog) {
  blogService.insert(blog);
  return blog.getId();
}

I only set the blog name, however, Blog.java contains default values:

private Boolean isDisabled = false;
private Boolean canCreateTags = true;
private Boolean canCreateCategories = true;
private Boolean hasRss = false;

This is the request body of my request :

{"organization":{"id":"1"},"description":"test"}

All the unsend values appear to be null.

However when I use the BlogDTO instead of Blog:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Long create(@RequestBody BlogDTO blog) {
  blogService.insert(blog);
  return blog.getId();
}

All the values are set with defaults.

  • Why is the instance not created with my defaults?
  • Why is the DTO instance created with defaults?
Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204

2 Answers2

1

Overriding the toString method of Blog.java with default values should solve this problem like below

public class Blog {

private Boolean isDisabled = false;
private Boolean canCreateTags = true;
private Boolean canCreateCategories = true;
private Boolean hasRss = false;

    @Override
        public String toString() {
            return "Blog{" +
                    "isDisabled='" + isDisabled + '\'' +
                    ", canCreateTags='" + canCreateTags + '\'' +
                    ", canCreateCategories=" + canCreateCategories +
                    '}';
        }
    }

Please refer this question and answer as a reference Spring 4 MVC - Rest service - use default values in beans

Aarish Ramesh
  • 6,745
  • 15
  • 60
  • 105
0

if you want to have default value you need to set explicitly while sending to post call body

spandey
  • 1,034
  • 1
  • 15
  • 30