Persistence @Column nullable = false can insert null

前端 未结 3 748
轮回少年
轮回少年 2021-01-18 08:08

I want to do this column can´t be null but when I insert in database one register values null this allows me inserted. I read documentation and I don´t know why doesn´t work

相关标签:
3条回答
  • 2021-01-18 08:44

    I think nullable is used if you generate the schema, using the implementation of the entitymanager. I don't know whether it is / has to be validated while persisting an entity as well.

    Maybe it helps if you use the @NotNull annotation, but this is NOT plain JPA. It's defined in the JSR-303

    There is a topic on Stackoverflow too that covers your question: Stackoverflow - Confusion notnull vs columnnullable false


    EDIT: In the JPA 2.1 Specification, there is this section:

    11.2.2.1 Column
    The following elements of the Column annotation are used in schema generation:
    name
    unique
    nullable
    columnDefinition table
    length (string-valued columns only) precision (exact numeric (decimal/numeric) columns only) scale (exact numeric (decimal/numeric) columns only) See section 11.1.9 for the rules that apply to these elements and column creation. The AttributeOverride annotation may be used to override column mappings.

    As there is no other hint given, I assume the following: If a JPA-conform EntityManager CREATES the schema, it HAS to apply the nullable constraint on the specific column by using an aequivalent DB related constraint (e.g. notnull) When you persist an entity, it is NOT checked by the Entitymanager BUT by the underlying databse. So if the DB raises an error, the EntityManager propagates this error up to the caller.

    If you create the table yourself without using the DB nullable constraint, then the entitymanager tries to persist the entity and gets NO error --> persist is okay althouh there are some null values that shouldn't be there.

    0 讨论(0)
  • 2021-01-18 08:49

    if you directly do insert in database then Hibernate or any persistence provider would not ne able to control you. try to insert using persistence provider.

    0 讨论(0)
  • 2021-01-18 08:51

    Probably in the base you already have that field with nulls In these cases you must change the nullity of the field manually MySql Query:

     alter table [table] modify [column] [[Column_Type] ej: vachar] not null;
    
    0 讨论(0)
提交回复
热议问题