0

Given I have entity Car with column model which doesn't accept NULLs

@Table(name = "CAR")
@Entity
public class Car extends AbstractEntity<Long> {

    @Column(name = "MODEL", nullable = false)
    private final String model;

}

When I prepare database schema, insert data (including NULLs in MODEL column) manually and start up application, it doesn't fail to start.

Why is that?

Do conditions specified in @Column annotation only apply for insert/update operations, not for read operations?

Patrik Mihalčin
  • 3,341
  • 7
  • 33
  • 68
  • Schema definition only. Use javax.validation if you want to prevent INSERTs/UPDATEs –  Mar 16 '18 at 10:36

1 Answers1

0

Yes, you can read null values with nullable = false. But when you try to save or update an entity with model = null, the JPA lever error will be thrown.

Check out the specification for nullable.

This JPA constraints just prohibit non-valid data from being written to the database, in order not to call it for no reason (by the way, you should have the same constraints in your database as you have in JPA).

These constraints have nothing to do with data that is already there. So that's why your application doesn't fail to start.

Have a look at this answer for better explanation.

htshame
  • 6,599
  • 5
  • 36
  • 56
  • What do you mean by JPA level constraint? Application needs to use JPA level for reading as well – Patrik Mihalčin Mar 16 '18 at 12:09
  • 1
    @PatrikMihalčin I mean it just prohibits non-valid data from being written to database (by the way, you should have the same constraints in the database) – htshame Mar 16 '18 at 12:11
  • @htshame Maybe, you can rework your answer to increase clarity. Second, please use/insert a reference on the behaviour of `nullable` via the official JPA specification document (section or page number). – MWiesner Mar 18 '18 at 13:12