天天看点

AccessType.PROPERTY和AccessType.FIELD的区别

 AccessType用来定义访问Entity的方式:

1. AccessType.PROPERTY的例子:

@Entity(access=AccessType.PROPERTY)

@Table(name = "Person")

public class Person implements Serializable {

    private Long id;

    // auto-generated PK

    @Column(name="Id")

    @Id(generator="PersonIdGenerator")

    @SequenceGenerator(name="PersonIdGenerator", sequenceName="PersonIdGenerator")

    public Long getId() {

        return id;

    }

    public void setId(Long personId) {

     this.id = personId;

    }

    ......

}

2. AccessType.FIELD的例子:

@Entity(access=AccessType.FIELD)

@Table(name = "Country")

public class Country implements Serializable {

@Id(generator="CountryIdGenerator")

    @SequenceGenerator(name="CountryIdGenerator", sequenceName="CountryIdGenerator")

    @Column(name="CountryId")

    public Long countryId;

    @Column(name="Name", length=128, nullable=false)

    public String name;

    ......

}

  • AccessType.PROPERTY: The EJB persistence implementation will load state into your class via JavaBean "setter" methods, and retrieve state from your class using JavaBean "getter" methods. This is the default.

         --> 通过getter和setter方法访问Entity的变量,可以把变量定义为private;

         --> 需要在getter方法上定义字段的属性;

  • AccessType.FIELD: State is loaded and retrieved directly from your class' fields. You do not have to write JavaBean "getters" and "setters". 

        --> 直接访问Entity的变量,可以不定义getter和setter方法,但是需要将变量定义为public;

        --> 需要在变量上定义字段的属性;

继续阅读