0

Supposed I have a User entity and it has a one to many relationship with Post

@OneToMany(
        cascade = CascadeType.ALL,
        orphanRemoval = true,
        fetch = FetchType.LAZY
)
@JoinColumn(
        name = "user_id",
        foreignKey = @ForeignKey(name = "fk"),
        referencedColumnName = "userId")
private List<Post> post = new ArrayList<>();

and this is my Post entity

@NotBlank(message = "test")
@Column(length = 50)
private String title;

@Column
private String post;

How can I validate the Post when Im inserting a new user? For example this what I passed on the request

{
        "name": "Test name",
        "username": "Test username",
        "post": [
            {
                "title": "asdasd",
                "post": "asdasd"
            }
        ]
}

If I pass a blank string on title

"title": "",

Im getting an error

Validation failed for classes .... during persist time for groups
Beginner
  • 1,700
  • 4
  • 22
  • 42
  • Can you provide more context for the error, maybe a stack trace? – Matt U Dec 10 '19 at 03:22
  • Validation failed for classes [com.test.app.api.models.Post] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='test', propertyPath=title, rootBeanClass=class com.test.app.api.models.Post, messageTemplate='test'}\n] – Beginner Dec 10 '19 at 03:25

2 Answers2

0

Did you add @Valid annotation for post method? Example:

 @PostMapping("/user")
 User insertNewUser(@Valid @RequestBody User user) {
    // Do something
  }
KyHuynh
  • 23
  • 5
0

You need to add a @Valid annotation to the post member of the User model. See this answer: https://stackoverflow.com/a/5142960/12431728

Matt U
  • 4,970
  • 9
  • 28