0

I'm building a rest API using Spring Boot rest services. I have a Java class:

class Person{
 int id;
 @notNull
 String name;
 @notNull
 String password;
 }

And I want to make an API to create a Person object. I will recieve a POST request with json body like:

{
"name":"Ahmad",
"password":"myPass",
"shouldSendEmail":1
}

As you can see there are an extra field "shouldSendEmail" that I have to use it to know if should I send an email or not after I create the Person Object. I am using the following API:

@RequestMapping(value = "/AddPerson", method = RequestMethod.POST)
public String savePerson(
        @Valid @RequestBody Person person) {

     personRepository.insert(person);

    // Here I want to know if I should send an email or Not

    return "success";
}

Is there a method to access the value of "shouldSendEmail" while I using the autoMapping in this way?

Ahmad Zahabi
  • 1,110
  • 12
  • 15

4 Answers4

0

You will need an intermediary DTO, or you will otherwise have to modify person to include a field for shouldSendEmail. If that is not possible, the only other alternative is to use JsonNode and manually select the properties from the tree.

For example,

@Getter
public class PersonDTO {
    private final String name;
    private final String password;
    private final Integer shouldSendEmail;

    @JsonCreator
    public PersonDTO(
        @JsonProperty("name") final String name,
        @JsonProperty("password") final String password,
        @JsonProperty("shouldSendEmail") final Integer shouldSendEmail
    ) {
        this.name = name;
        this.password = password;
        this.shouldSendEmail = shouldSendEmail;
    }
}
0

You can use @RequestBody and @RequestParam together as following

.../addPerson?sendEmail=true

So send the “sendEmail” value as request param and person as request body

Spring MVC - Why not able to use @RequestBody and @RequestParam together

Amr Alaa
  • 545
  • 3
  • 7
0

You have mutli solutions

1 - You can put @Column(insertable=false, updatable=false) above this property

2 - send it as request param @RequestParam @RequestMapping(value = "/AddPerson", method = RequestMethod.POST) public String savePerson( @Valid @RequestBody Person person, @RequestParam boolean sendMail) {}

3- use DTO lets say PersonModel and map it to Person before save

Samir Ghoneim
  • 591
  • 1
  • 6
  • 14
0

There's many options for you solve. Since you don't want to persist the shouldSendEmail flag and it's ok to add into you domain class, you can use the @Transient annotation to tell JPA to skip the persistence.

@Entity
public class Person {

    @Id 
    private Integer id;

    @NotNull
    private String name;

    @NotNull
    private String password;

    @Transient
    private Boolean shouldSendEmail;

}

If you want more flexible entity personalizations, I recommend using DTO`s.

MapStruct is a good library to handle DTO`s

Deividi Cavarzan
  • 10,034
  • 13
  • 66
  • 80