techPackets
techPackets

Reputation: 4504

Stating table column properties with Hibernate

I am using Hibernate in my project. I have a database schema already created.

I see in the tutorials online

@Column(name = "STOCK_ID", unique = true, nullable = false)
    public Integer getStockId() {
        return this.stockId;
    }

the columns properties like unique nullable etc are being used. My question is do I need to specify these properties when I already have a db schema prepared prehand with the columns being given all the not null and all the checks while creating the tables?.

Upvotes: 1

Views: 348

Answers (2)

JB Nizet
JB Nizet

Reputation: 691635

unique is only used when generating the database schema from the JPA annotations. nullable = false allows JPA to be more efficient: if the value is null when it writes the entity to the database, it doesn't even have to execute the insert/update query and can throw an exception immediately.

Even if that's not absolutely necessary, I like having these informations in the mapping for documentation purposes. Being able to know immediately from the code, without looking at the database schema, that an attribute is nullable or not, is useful.

Upvotes: 1

K.C.
K.C.

Reputation: 2112

No you don't, only the required parameters in the Hibernate annotations have to be filled in. But the optional parameters frequently have default values. Your DB will have to be compatible with the default values, else you will have to fill in the values you use.

Upvotes: 1

Related Questions