續前節。
我們看到,NetBeans通過自動產生JPA實體為我們節省了大量時間。 “Don’t use wizard code you don’t understand.”———Andrew Hunt and Dave Thomas
咱們看看產生的實體代碼,你自己理解一下。
Listing 1. Examining a Generated Entity
package com.ensode.petclinicjavaee.entity; //imports omitted for brevity @Entity
@Table(name = "owners", catalog = "petclinic", schema = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Owner.findAll", query = "SELECT o FROM Owner o"),
@NamedQuery(name = "Owner.findById",
query = "SELECT o FROM Owner o WHERE o.id = :id"),
@NamedQuery(name = "Owner.findByFirstName",
query = "SELECT o FROM Owner o WHERE o.firstName = :firstName"),
@NamedQuery(name = "Owner.findByLastName",
query = "SELECT o FROM Owner o WHERE o.lastName = :lastName"),
@NamedQuery(name = "Owner.findByAddress",
query = "SELECT o FROM Owner o WHERE o.address = :address"),
@NamedQuery(name = "Owner.findByCity",
query = "SELECT o FROM Owner o WHERE o.city = :city"),
@NamedQuery(name = "Owner.findByTelephone",
query = "SELECT o FROM Owner o WHERE o.telephone = :telephone")})public class Owner implements Serializable { private static final long serialVersionUID = 1L; @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "id", nullable = false) private Integer id; @Size(max = 30)
@Column(name = "first_name", length = 30)
private String firstName; @Size(max = 30)
@Column(name = "last_name", length = 30)
private String lastName; @Size(max = 255)
@Column(name = "address", length = 255)
private String address; @Size(max = 80)
@Column(name = "city", length = 80) private String city; @Size(max = 20)
@Column(name = "telephone", length = 20)
private String telephone; @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private Collection<Pet> petCollection; public Owner() { } public Owner(Integer id) { this.id = id; } //getters and setters omitted for brevity @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id // fields are not set if (!(object instanceof Owner)) { return false; } Owner other = (Owner) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.ensode.petclinicjavaee.entity.Owner[ id=" + id + " ]"; } }
這些代碼很平淡,很俗,只是標準JavaBean,帶著私人屬性和公開的getter和setter.關鍵是註解。.(對註解的理解請看原文http://www.oracle.com/technetwork/articles/java/springtojavaee-522240.html)
Conclusion
看到了吧,使用JPA和NetBeans開發資料層多簡單,因為NB嚮導幫我們產生了大部分代碼。在後面的第二部分,我們將看到NB幫我們產生其他層。