官术网_书友最值得收藏!

  • EJB 3 Developer Guide
  • Michael Sikora
  • 303字
  • 2021-07-02 11:34:55

Field-Based Annotations

Recall we used a property-based annotation for the primary key @Id in the Customer entity. This results in the persistence engine using getter and setter methods to access and set the entity state. In this section we will modify the Customer entity to use field-based, rather than property-based annotations. The following listing demonstrates this:

@Entity
public class Customer implements java.io.Serializable {
@Id
private int id;
private String firstName;
@Basic
private String lastName;
public Customer() {};
public Customer(int id, String firstName,
String lastName){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFirstname() { return firstName; }
public void setFirstname(String firstName) {
this.firstName = firstName;
}
public String toString() {
return "[Customer Id =" + id + ",first name=" +
firstName + ",last name=" + lastName + "]";
}
}

Note that we have placed the primary key @Id annotation immediately before the field declaration. If we use a field-based annotation then all other annotations, other than class level annotations such as @Entity, must also be field-based annotations. In the case of field-based annotations the persistence engine will use reflection to access and set the entity state. Getter and setter methods may be present in the entity but they are ignored by the persistence engine. To demonstrate this point we have removed the getLastName() and setLastName() methods from the Customer entity.

We have seen that attributes other than the primary key are mapped to a database by default. We call these mappings basic mappings. A basic mapping is used where the attribute is a Java primitive type or any Serializable type such as a String. We can explicitly flag these mappings using the @Basic annotation. We have done this for the lastName field.

主站蜘蛛池模板: 建昌县| 子洲县| 垦利县| 泰安市| 北碚区| 临颍县| 安塞县| 安福县| 合水县| 土默特左旗| 沾化县| 科技| 渭源县| 禄劝| 凤山县| 林甸县| 丹巴县| 山阳县| 桓仁| 江口县| 云梦县| 澜沧| 中宁县| 庄河市| 章丘市| 汨罗市| 平罗县| 兴业县| 鄱阳县| 金门县| 台前县| 婺源县| 涞源县| 交城县| 灵丘县| 浙江省| 镇巴县| 长乐市| 班戈县| 海阳市| 丹凤县|