hibernate - spring boot - calculated field -


so, have entity, has field start_date (java.util.date type).

i want have field, automatically populate integer corresponds day of week (as number 1 sunday, 2 monday, etc.) of starting date.

here's fragment of entity:

@id @generatedvalue(strategy = generationtype.auto) private integer id;  @datetimeformat(pattern = "yyyy-mm-dd") @temporal(temporaltype.date) private date start_date; 

i've tried add calculated field in following way:

@column(name = "weekday") @formula("(select dayofweek(l.start_date) lesson l l.id = id)") private integer weekday; 

however, when looking @ lesson table in h2 console, there's no such column "weekday"

i tried other option - without @formula annotation , setter takes start_date parameter, guess setter never called, since column "weekday" populated null. here's setter i've tried use alternative solution:

    public void setweekday(date start_date) {     calendar c = calendar.getinstance();     c.settime(start_date);     this.weekday = c.get(calendar.day_of_week); } 

it's obvious i'm missing here, it's because i'm still learning spring boot...

to sum - want have column in table lesson, calculated column of same table.

@formula means field calculated rules. entity field not column in db. field calculating each entity in loading time specified rule.

if annotation @column(name = "weekday") work near @formula confused if expect in loaded entity same value in db here calculated 1 , different (inconsistent situation).

if want save here value lesson table should remove @formula , use @entitylisteners({yourentityjpacallbackslistener.class}) in spring bean yourentityjpacallbackslistener can define methods marked @preupdate or @prepersist , use correspond operations set calculated value weekday.

for example:

@entitylisteners({yourentityjpacallbackslistener.class}) @entity public class yourentity{     // code }  @component public class yourentityjpacallbackslistener {     @autoware     lessonrepository lessonrepository;      @preupdate     void preupdate(yourentity yourentity) {         if (recurrentrulerepository.exists(yourentity.getid())) {             integer weekday = lessonrepository.findone(yourentity.getid());             yourentity.setweekday(weekday);         }     }  } 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -