简体   繁体   中英

Setting default primitive boolean value

I have a basic SpringBoot/Hibernate application that deals with a database. I have a column in an Oracle table that represents a boolean value. At the database level, it is represented this way - P_IND CHAR(1 BYTE) DEFAULT 'N' NOT NULL

At the entity level, I am mapping it this way -

@Column(name = "P_IND")
@Type(type = "yes_no")
private boolean ind;

When creating new records, the default needed to be an 'N' and this worked as expected. Now the default needs to be true ('Y' in the database). I could do it this way

a) private boolean ind = true;

or add this annotation

b) @ColumnDefault("true")

  1. Isn't a) more advantageous in that you could create/persist entities with both true/false values?
  2. Would b) allow you to create both ( ind is a primitive boolean) and if so, is the annotation a better way of doing it?

They do two different things.

@ColumnDefault is an Hibernate ORM specific annotation (not JPA). It identifies the default value that Hibernate will use in the column definition when it's generating the schema at start up. It means that's only used when Hibernate creates the column.

private boolean ind = true;

Using a primitive type means that the value will always be true or false (I think in Java the default is false ) during the persist or updates. So the @ColumnDefault doesn't really matter (unless you run custom insert queries without Hibernate ORM).

If you change the type to Boolean , then ind can be null. This means that the default value used on insertion will be the one used when the column was created. If you have created the database using Hibernate ORM, it's the value in @ColumnDefault .

Anyway, it seems you need both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM