Friday, March 16, 2007
10 Tips utk Belajar Hibernate (Kelas Permulaan)
- Create a new class, implementing the Serializable interface.
- Add class variables id and version, which are both of type Long. These variables are the primary key and the version number for optimistic locking respectively.
- Add any properties you need.
- Write a default constructor. All variables of type Collection, List, Set, ... should be initialized here.
- Generate getters and setters for all properties:
- id should have a public getter, and no setter
- version should have a protected getter, no setter
- variables of type Collection, List, Set, ... have a public getter and no setter. The public getter preferably return an unmodifiable list.
- Add annotations to the class variables rather than to the getters or setters.
- class-level: @Entity and maybe @Table(name=xxx). When using inheritance you will also need to specify the inheritance type.
- id: @Id and @GeneratedValue(strategy = GenerationType.AUTO)
- version: @Version
- variables: Hibernate Validator annotations such as @NotNull, @Length, @Range, ...
- variables: @Column(name=xxx), but only when the column name is not the same as the variable name
- variables: @OneToOne, @OneToMany, @ManyToOne or @ManyToMany in the case of relations.
- When using relations, make sure that the relation is bidirectional. For the sake of simplicity, I create utility methods that handle this on 1 side of the relation: properties of type Collection have utility methodes addXXX and removeXXX. The corresponding setter on the other side of the relation is protected, and called from the utility methods.
- Implement equals and hashcode methods.
- Always compare values using the getters of the properties, not the class variables directly.
- Do not compare id and version
- Do not compare Collections
- Add a mapping element to the hibernate.cfg.xml file
- You're done!
Subscribe to:
Posts (Atom)