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.