0

this is more like a "best-practice" question. I am playing around with spring-boot and hibernate to build a small CRUD Service.

Let's assume, I have an entity called Customer (which is annotated as hibernate entity...) which has all kinds of properties like name, middlename, lastname, ...

@Entity
@Table(name = "OCUS")
public CustomerEntity {
    // Props
    @Column(name = "Name")
    @SerializedName("name")
    @Expose
    private String name;

    @Column(name = "MName")
    @SerializedName("mname")
    @Expose
    private String middlename;
    ...
    @Column(name = "Status")
    @SerializedName("status")
    @Expose
    private CustomerEntityType status = CustomerEntityType.NEW;
    @Column(name = "Valid")
    @SerializedName("valid")
    @Expose
    private Boolean valid = false;

    // getters and setters
}

I also created a CustomerEntityRepository which extends the JPARepository like this: @Repository public interface CustomerEntityRepository extends JpaRepository {

}

After that, I created a RestController to have GET/POST/DELETE/... Methods for my customers.

@RestController
@RequestMapping("/v1/customers")
public class CustomerRestController {

    @Autowired
    CutomerEntityRepository customerRepo;

    @PostMapping
    public ResponseEntity<CustomerEntity> createCustomer(@RequestBody CustomerEntity customer) {

    customerRepo.save(customer);
    // ... Build ResponseEntity...
    }
...
}

Let's assume, the RequestBody does not include all properties from my CustomerEntity, maybe I have Properties like "status" or "valid".

e.g.:

{
    "name" : "Jon",
    "lastName" : "Doe",
    "field1" : "value1",
    ...
}

My question now is:

What has to be done, so that the customer I am going to save into the CustomerEntityRepository gets all the standard values set (see property: status and valid) without having to check all properties if it was included in the request body.

My Goal is only to save customers, which represent my CustomerEntity with all the default values when getting customers via my Rest Controller.

Thank you for any feedback

Robert

[EDIT]:

Because my question seems to be unclear, I'll try to elaborate it further:

Assume my REST Endpoint receives the following Json which represents a CustomerEntity:

{
    "name" : "Jon",
    "lastName" : "Doe"
}

The Deserializer from the spring-boot packages seems to look up for a suitable constructor of my customerentity. So if I implement a constructor like this:

public CustomerEntity(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

The deserializer tries to construct the customerEntity nicely via this constructor. All my standard values like valid will be set to false and status will be set to CustomerEntityType.NEW;

Let's assume the next incoming Json is:

{
    "name" : "Jon",
    "lastName" : "Doe",
    "middleName" : "Harry"
}

But this time, I have no suitable constructor to create the customer via a constructor. So creating a vast number of constructors to represent all possible variants is not the right way, I think.

I don't know how exactly the deserializer now creates my CustomerEntity object out of the JSON, but the object I receive in my method:

    @PostMapping
    public ResponseEntity<CustomerEntity> createCustomer(@RequestBody CustomerEntity customer) {

    customerRepo.save(customer);
    // ... Build ResponseEntity...
    }

Has only set the 3 properties: name, lastName, middleName and all other properties of CustomerEntity are null. And I need to prevent such CustomerEntities to be saved to the database.

Hope this case is now more clear.

2 Answers2

0

You can use hibernate validator which is an implementation of JSR 380.

and btw, if you are using any of the annotation provided by hibernate-validator, you'll have to use @valid annotation in your controller from package javax.validation.

so your controller will be something like,

@PostMapping
public ResponseEntity<CustomerEntity> createCustomer(@Valid @RequestBody CustomerEntity customer) { }

you can read more about that in detail here : https://spring.io/guides/gs/validating-form-input/ http://hibernate.org/validator/

Pratik Shah
  • 1,782
  • 1
  • 15
  • 33
  • Hi, my question is not about validate, if the Json was a valid CustomerEntity. I think this is already done by the Deserializer from the webpackage. I am going to edit my question to make it more clear. – Robert Zieschang Jun 20 '18 at 07:41
  • You don't need constructor based on the request body json. the data got populated based on the getter & setter method, so if some of the fields are null even though you are sending them in the request body, then please check getter & setters are correct for those fields, & if you don't want such request to get processed , then put `@Valid` annotation as mentioned in answer & put `@NotNull` annotation in your request body DTO, i.e. CustomerEntity – Pratik Shah Jun 20 '18 at 09:42
  • As I said, it's not about validation. When you design a class, you can set standard values like `private boolean boolVal = true` which is then set to true, even if it was not set in any constructor or set via setter Method. When the request body json is deserialized from spring-boot and the object is injected in my createCustomer method these standard values for the class properties does not get set. – Robert Zieschang Jun 20 '18 at 10:40
  • I am getting default values set on the field in the request body DTO without any change. – Pratik Shah Jun 20 '18 at 11:30
  • That is odd. Can you show me your entity, Request Body Json and the Post Method with all annotations? Thank you. – Robert Zieschang Jun 20 '18 at 11:37
  • Sure, https://gist.github.com/peanutpi/2c40389695bb0890957b5d70204d8987 – Pratik Shah Jun 20 '18 at 11:58
0

Not eally sure what you are asking , if you want to set the default values of fields/attribute you can use :

@Column(name="status", columnDefinition="Decimal(10,2) default '100.00'")

ref: Setting default values for columns in JPA

SArya
  • 43
  • 6