1 package ejava.jpa.example.validation; 2 3 import java.math.BigDecimal; 4 import java.text.DateFormat; 5 import java.text.NumberFormat; 6 import java.text.SimpleDateFormat; 7 import java.util.Date; 8 import java.util.HashSet; 9 import java.util.Set; 10 11 import javax.persistence.*; 12 import static javax.persistence.CascadeType.*; 13 import javax.validation.Valid; 14 import javax.validation.constraints.NotNull; 15 import javax.validation.constraints.Past; 16 17 @Entity 18 @Table(name="VALIDATION_PURCHASE") 19 public class Purchase { 20 @Id @GeneratedValue 21 private int id; 22 23 @Temporal(TemporalType.TIMESTAMP) 24 @NotNull(message="purchase requires a date") 25 @Past(message="future purchases not allowed") 26 private Date date; 27 28 @OneToMany(fetch=FetchType.LAZY, cascade={PERSIST, REMOVE, DETACH}) 29 @JoinColumn(name="PURCHASE_ID") 30 @Valid 31 private Set<PurchaseItem> items; 32 33 public int getId() { return id; } 34 35 public Date getDate() { return date; } 36 public Purchase setDate(Date date) { 37 this.date = date; 38 return this; 39 } 40 41 public Set<PurchaseItem> getItems() { 42 if (items==null) { 43 items = new HashSet<PurchaseItem>(); 44 } 45 return items; 46 } 47 public Purchase setItems(Set<PurchaseItem> items) { 48 this.items = items; 49 return this; 50 } 51 public Purchase addItem(PurchaseItem item) { 52 getItems().add(item); 53 return this; 54 } 55 56 public BigDecimal getTotal() { 57 BigDecimal total = new BigDecimal(0); 58 for (PurchaseItem item : getItems()) { 59 total.add(item.getTotal()); 60 } 61 return total; 62 } 63 64 @Override 65 public String toString() { 66 DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 67 NumberFormat nf = NumberFormat.getCurrencyInstance(); 68 StringBuilder text = new StringBuilder(); 69 text.append("#" + id); 70 text.append(date==null?null : df.format(date)); 71 text.append("\n"); 72 for (PurchaseItem item : getItems()) { 73 text.append(item.toString()).append("\n"); 74 } 75 text.append("total=").append(nf.format(getTotal())); 76 77 return text.toString(); 78 } 79 80 }