4.1. 一个简单的POJO例子

大多数Java程序需要用一个持久化类来表示猫科动物。

  1. package eg;
  2. import java.util.Set;
  3. import java.util.Date;
  4. public class Cat {
  5. private Long id; // identifier
  6. private Date birthdate;
  7. private Color color;
  8. private char sex;
  9. private float weight;
  10. private int litterId;
  11. private Cat mother;
  12. private Set kittens = new HashSet();
  13. private void setId(Long id) {
  14. this.id=id;
  15. }
  16. public Long getId() {
  17. return id;
  18. }
  19. void setBirthdate(Date date) {
  20. birthdate = date;
  21. }
  22. public Date getBirthdate() {
  23. return birthdate;
  24. }
  25. void setWeight(float weight) {
  26. this.weight = weight;
  27. }
  28. public float getWeight() {
  29. return weight;
  30. }
  31. public Color getColor() {
  32. return color;
  33. }
  34. void setColor(Color color) {
  35. this.color = color;
  36. }
  37. void setSex(char sex) {
  38. this.sex=sex;
  39. }
  40. public char getSex() {
  41. return sex;
  42. }
  43. void setLitterId(int id) {
  44. this.litterId = id;
  45. }
  46. public int getLitterId() {
  47. return litterId;
  48. }
  49. void setMother(Cat mother) {
  50. this.mother = mother;
  51. }
  52. public Cat getMother() {
  53. return mother;
  54. }
  55. void setKittens(Set kittens) {
  56. this.kittens = kittens;
  57. }
  58. public Set getKittens() {
  59. return kittens;
  60. }
  61. // addKitten not needed by Hibernate
  62. public void addKitten(Cat kitten) {
  63. kitten.setMother(this);
  64. kitten.setLitterId( kittens.size() );
  65. kittens.add(kitten);
  66. }
  67. }

这里要遵循四条主要的规则: