반응형

JPA 가 엔티티 데이터에 접근하는 방식을 지정한다.

1. AccessType.FIELD : 필드에 직접 접근한다.

@Access(AccessType.FIELD)
private String address1;

2. AccessType.PROPERTY : 프로퍼트로 접근한다. 

@Access(AccessType.PROPERTY)
public String getAddress2() {
	return address1 + address2;
}

3. AccessType 이 지정되지 않은 경우는 @Id 위치에 따라 지정된다.

@Entity
public class OrderInfo {
    @Id
    private Long id;
    private String address1;
    @Transient
    private String address2;

    @Access(AccessType.PROPERTY)
    public String getAddress2() {
        return address1 + address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }
}

- @Id 위치가 필드에 있기때문에 기본적으로 AccessType.FIELD 가 적용된다. AccessType.PROPERTY를 같이 적용하기 위해서는 메소드 위에 AccessType.PROPERTY 를 넣어주면 된다.

4. 기타 설명들

@Access is used to specify how JPA must access (get and set) mapped properties of the entity. If access type is set to FIELD, the values will directly be read/set on the field, bypassing getters and setters. If set to PROPERTY, the getters and setters are used to access the field value.

FIELD 로 정의하면 다이렉트로 field를 read/set 하고 PROPERTY로 설정하면 getter, setter 메소드를 통해서 접근한다.
https://stackoverflow.com/questions/19264871/what-is-the-use-of-the-access-annoation-in-jpa-means-at-the-entity-level

 

If you use field-based access, your JPA implementation uses reflection to read or write your entity attributes directly. It also expects that you place your mapping annotations on your entity attributes. If you use property-based access, you need to annotate the getter methods of your entity attributes with the required mapping annotations. Your JPA implementation then calls the getter and setter methods to access your entity attributes.

5 reasons why you should use field-based access
Better readability of your code
Omit getter or setter methods that shouldn’t be called by your application
Flexible implementation of getter and setter methods
No need to mark utility methods as *@Transient*
Avoid bugs when working with proxies

https://thorben-janssen.com/access-strategies-in-jpa-and-hibernate/

 

 

728x90
반응형

+ Recent posts