2

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

Anmol Bhaskar
  • 117
  • 2
  • 6

2 Answers2

1

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.

JoeG
  • 7,191
  • 10
  • 60
  • 105
  • 1
    Nullable is not a JPA related annotation. JPA and Java allows fields to be nullable by default, but this is set within the column definition if you wish to add a constraint on the database column. – Chris Jul 21 '17 at 14:30
0

According my experience, setting any default values of attributes in Hibernate entity bean can be a reason of unnecessary update commands that Hibernate can generate because it might decide that entity was changed after reading it from database even if application does not actually change entity. Similar question was already discussed here: Setting default values for columns in JPA

Evgeny Semionov
  • 323
  • 2
  • 9