0

I am using MySQL and JPA. When I use @NotNull annotation, the not null constraint isn't applied to the table schema. @Column(nullable = true) works properly though. But @NotNull should work as what I found here https://www.baeldung.com/hibernate-notnull-vs-nullable.

Here are the code

application.yml

spring:
  jpa:
    hibernate:
      ddl-auto: create-drop
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    properties:
      hibernate:
        validator:
          apply_to_ddl: true
        format_sql: true

build.gradle

plugins {
    id 'org.springframework.boot' version '2.5.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'xxx'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '16'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    runtimeOnly 'mysql:mysql-connector-java'
    implementation 'javax.validation:validation-api:2.0.1.Final'
    implementation 'org.springframework.boot:spring-boot-starter-validation:2.5.2'
    implementation 'org.hibernate.validator:hibernate-validator:7.0.1.Final'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

}

test {
    useJUnitPlatform()
}

model

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;

@Entity
public class Item {

    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    private BigDecimal price;
}

Table Schema

create table item
(
    id    bigint         not null
        primary key,
    price decimal(19, 2) null
);

price should have not null constraint.

I have tried setting apply_to_ddl: true manually.

S. Anushan
  • 680
  • 1
  • 6
  • 11
Huakun Shen
  • 102
  • 4
  • This question has been covered in detail [here](https://stackoverflow.com/questions/7439504/confusion-notnull-vs-columnnullable-false-with-jpa-and-hibernate) – Superchamp Jul 13 '21 at 05:49

0 Answers0