병원
엔티티에 주소에 대한 정보가 들어감주소
를 나타내는 컬럼이 여러가지가 있는데, 그것을 묶어서 임베디드타입의 필드로 지정@Entity
@Getter
@NoArgsConstructor
public class Hospital {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long hosId;
private String hosName;
//주소를 나타내는 필드들
private String jibunAddress;
private String roadAddress;
private String sangse;
private double x;
private double y;
}
병원
엔티티는 병원 아이디, 병원 이름, 병원 주소의 정보를 갖고 있는 것인데,지번 주소
, 도로명 주소
, 상세 주소
, 위도
, 경도
를 갖게 된다.주소
에 관련된 필드들을 임베디드 타입을 사용하여 조금 더 객체지향적으로 바꿈@Entity
@Getter
@NoArgsConstructor
public class Hospital {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long hosId;
private String hosName;
//임베디드 타입 사용
@Embedded
private Address hosAddress;
}
@Embeddable
public class Address {
private String jibunAddress;
private String roadAddress;
private String sangse;
private double x;
private double y;
}
임베디드 타입의 객체는 어떤 엔티티의 필드 값으로 들어가 있는 값이므로, 공유되어선 안된다.
Setter
를 사용하지 않는다.primitive type
이라고 보면, int를 3에서 5로 바꾸면 값 자체가 바뀌는 것이다.불변(값)
자체로 보고 객체를 수정하면 안된다Hospital hospital = em.find(Hospital.class, id);
// 구 주소는 hospital에 새로운 주소를 입력하면 CG에 의해서 지워짐
Address oldAddress = hospital.getHosAddress();
// 새로운 주소
Address newAddress = new Address("구주소", "신주소", "상세주소", 위도, 경도);
// 영속성 컨텍스트의 변경감지에 의해서 커밋 시 주소컬럼들 변경
hospital.setAddress(newAddress);