Christian
Christian

Reputation: 1

Can @Valid validate that the method argument is not null?

I'm using Jakarta Validation (jakarta.validation) in a Quarkus application and I want to ensure that an Article object passed to my service methods is not null before applying field-level validation using @Valid.

Here's my Article entity:

@Entity
@Table(name = "article")
@Data
@NoArgsConstructor
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name", nullable = false)
    @NotNull(message="Article name cannot be null.")
    @NotEmpty(message="Article name cannot be empty.")
    private String name;

    @Column(name = "articlenumber", nullable = false)
    @NotNull(message="Article number cannot be null.")
    @NotEmpty(message="Article number cannot be empty.")
    private String articlenumber;
}

In my ArticleService, I use @Valid in a method like this:

@Transactional
public Article createArticle(@Valid Article article) {
    if (articleRepository.findByArticleNumber(article.getArticlenumber()) != null) {
        throw new IllegalArgumentException("Article with this articlenumber already exists.");
    }
    articleRepository.persist(article);
    return article;
}

Can @Valid enforce that the object itself is not null, just like it does for its fields without having a custom null check in the service?

Upvotes: 0

Views: 54

Answers (0)

Related Questions