1 package org.hibernate.ejb.test; 3 4 import java.util.Calendar ; 5 import java.util.Date ; 6 import java.util.GregorianCalendar ; 7 import javax.persistence.Basic; 8 import javax.persistence.Entity; 9 import javax.persistence.EntityListener; 10 import javax.persistence.GeneratorType; 11 import javax.persistence.Id; 12 import javax.persistence.PostLoad; 13 import javax.persistence.PostUpdate; 14 import javax.persistence.TemporalType; 15 import javax.persistence.Transient; 16 17 20 @Entity 21 @EntityListener(LastUpdateListener.class) 22 public class Cat { 23 private Integer id; 24 private String name; 25 private Date dateOfBirth; 26 private int age; 27 private Date lastUpdate; 28 private int manualVersion = 0; 29 private int postVersion = 0; 30 31 @Id(generate = GeneratorType.AUTO) 32 public Integer getId() { 33 return id; 34 } 35 36 public void setId(Integer id) { 37 this.id = id; 38 } 39 40 public String getName() { 41 return name; 42 } 43 44 public void setName(String name) { 45 this.name = name; 46 } 47 48 public Date getDateOfBirth() { 49 return dateOfBirth; 50 } 51 52 public void setDateOfBirth(Date dateOfBirth) { 53 this.dateOfBirth = dateOfBirth; 54 } 55 56 public int getManualVersion() { 57 return manualVersion; 58 } 59 60 public void setManualVersion(int manualVersion) { 61 this.manualVersion = manualVersion; 62 } 63 64 @Transient 65 public int getAge() { 66 return age; 67 } 68 69 public void setAge(int age) { 70 this.age = age; 71 } 72 73 @Basic(temporalType = TemporalType.TIMESTAMP) 74 public Date getLastUpdate() { 75 return lastUpdate; 76 } 77 78 public void setLastUpdate(Date lastUpdate) { 79 this.lastUpdate = lastUpdate; 80 } 81 82 public int getPostVersion() { 83 return postVersion; 84 } 85 86 public void setPostVersion(int postVersion) { 87 this.postVersion = postVersion; 88 } 89 90 @PostUpdate 91 public void someLateUpdateWorking() { 92 this.postVersion++; 93 } 94 95 @PostLoad 96 public void calculateAge() { 97 Calendar birth = new GregorianCalendar (); 98 birth.setTime( dateOfBirth ); 99 Calendar now = new GregorianCalendar (); 100 now.setTime( new Date () ); 101 int adjust = 0; 102 if ( now.get( Calendar.DAY_OF_YEAR ) - birth.get( Calendar.DAY_OF_YEAR ) < 0 ) { 103 adjust = -1; 104 } 105 age = now.get( Calendar.YEAR ) - birth.get( Calendar.YEAR ) + adjust; 106 } 107 } 108 | Popular Tags |