Hello, good afternoon.
Let us see today how to map in JPA the Date attribute and the Enum attribute.
Maybe there are people that almost got a heart attack when they hear about Date in Java. The APIs can be a little complex to those that are learning about Java.
Fortunately we can find a good solution in JPA to persist a Date attribute. The @Temporal annotation allows us to map 3 options:
- Just date.
- Just time.
- Date and Time.
Check the code bellow:
@Temporal(value=TemporalType.DATE) private Date onlyDate; @Temporal(value=TemporalType.TIME) private Date onlyTime; @Temporal(value=TemporalType.TIMESTAMP) private Date dateAndTime;
It is a very simply way to persist a date field. You can choose the attribute information type just using the right annotation type.
To map an Enum is easy as mapping a Date. To map an Enum in JPA you just have to write the code bellow:
@Enumerated private Enum vaules; @Enumerated(value=EnumType.STRING) private Enum vauleAsString; @Enumerated(value=EnumType.ORDINAL) private Enum vauleAsNumber;
You may leave the @Enumerated without parameters, or you may define it as: String or Ordinal.
If your table is not a huge table, you can define your Enum field as String. It is easier to read a status = ‘OK’ or ‘NOK’ than status = 1 (same than status = ‘OK’).
Notice that a query using a String as parameter will use more processing from the database than using a number; if your table is a huge table, it is a better idea to have your status as number and another table to store the status description.
Another solution (less elegant) it would be having both columns in the same table, a column with status = ‘1’ and another column with status_type = ‘OK’.
I hope this little post might be able to help you.
If you have any Doubts/Suggestions just post it.
See you soon.