BAEL-3385: Hibernate @NotNull vs @Column(nullable = false) (#8194)

* BAEL-3385: Hibernate @NotNull vs @Column(nullable = false)

* BAEL-3385: Fix test's assertion
This commit is contained in:
kwoyke 2019-11-20 10:30:16 +01:00 committed by Grzegorz Piwowarek
parent d7279d6f38
commit 256c40aa3f
5 changed files with 64 additions and 0 deletions

View File

@ -22,6 +22,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>

View File

@ -0,0 +1,9 @@
package com.baeldung.h2db.springboot.daos;
import com.baeldung.h2db.springboot.models.Item;
import org.springframework.data.repository.CrudRepository;
import java.math.BigDecimal;
public interface ItemRepository extends CrudRepository<Item, BigDecimal> {
}

View File

@ -0,0 +1,18 @@
package com.baeldung.h2db.springboot.models;
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;
}

View File

@ -3,6 +3,10 @@ spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.validator.apply_to_ddl=false
#spring.jpa.properties.hibernate.check_nullability=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
debug=true

View File

@ -0,0 +1,29 @@
package com.baeldung;
import com.baeldung.h2db.springboot.SpringBootH2Application;
import com.baeldung.h2db.springboot.daos.ItemRepository;
import com.baeldung.h2db.springboot.models.Item;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.validation.ConstraintViolationException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootH2Application.class)
public class ItemIntegrationTest {
@Autowired
private ItemRepository itemRepository;
@Test
public void shouldNotAllowToPersistNullItemsPrice() {
assertThatThrownBy(() -> itemRepository.save(new Item()))
.hasRootCauseInstanceOf(ConstraintViolationException.class)
.hasStackTraceContaining("must not be null");
}
}