续前节。
我们看到,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帮我们生成其他层。