Search code examples
javajpaeclipselink

Assigning NULL value to the persistent column


I am new to JPA so pardon if my question seems to be trivial.

I have an entity named customer

@Entity("CUSTOMER_DETAILS")
public class Customer {

    @Id
    @Column(name = "customer_id")
    private String customerId = null;    

    @Column(name = "name")
    private String name = null;

    @Column(name = "Id")
    private String Id = null;

    @Transient
    private List<Coupons> coupons;
}

One of my seniors was stating that setting the persistence columns to null is a bad practice. Kindly clarify


Solution

  • IIRC, fields on a JPA Entity bean are not nullable by default. Thus, setting them to null and subsequently setting them to some valid value would rightly be perceived as "bad practice".

    To make column values allow nulls, one needs to add the @Nullable annotation after the @Column one. Then as mentioned in the comments, values that are not set will automatically be saved as null column values in your database. Reads (or gets) will pull these out properly so there is not a use case where they need to be set as you have them.