builder로 생성하면 list초기화가 안된다

김민지·2022년 10월 19일
0

JPA

목록 보기
5/27
@Test
	@Transactional
	void contextLoads() {
		Member member = Member.builder().name("김길동").build();
		em.persist(member);//1차 캐시에 저장
		Team team = Team.builder().name("A팀").build();
		em.persist(team);//1차 캐시에 저장
		team.settingMember(member);
		Member findMember = em.find(Member.class, member.getId());
		Team findTeam = em.find(Team.class, team.getId());
		Assertions.assertEquals(findMember, findTeam.getMemberList().get(0));
		Assertions.assertEquals(findTeam, findMember.getTeam());

	}
@Entity
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@SequenceGenerator(name="TEAM_SEQUENCE",
        sequenceName = "TEAM_SEQ"
)
public class Team {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TEAM_SEQUENCE")
    @Column(name = "TEAM_ID")
    private Long id;

    @Column(unique = true)
    private String name;


    @OneToMany(fetch = FetchType.LAZY, mappedBy = "team")
    private List<Member> memberList = new ArrayList<>();

    public void settingMember(Member member){
        member.setTeam(this);
        //memberList = new ArrayList<>(); builder로 생성하면 이주석을 해제해줘야지만 테스트통과뜸
        this.memberList.add(member);
    }

}
  • 그럼 private List<Member> memberList = new ArrayList<>(); 할당은 왜 해주는 것일까?
  • 예를들어 name만 받는 생성자를 생성해준다고 하면 그때의 경우는 new ArrayList로 할당해준다.
  • builder와 name만 받는 생성자의 차이는 무엇일까? 왜 name만 받는 생성자의 경우는 new ArrayList할당까지 가능한것일까?
  • team.class를 확인해보자
  • 들어온값이 없어서 null이 들어간 것이었다.
  • java 파일을 컴파일하면 class파일이 만들어진다.
  • class파일은 원래 바이트 코드가 들어있어야하지만 보기편하라고 디컴파일된 파일을 보여주는 것 같다
    class파일을 열어보니 컴파일후에 어노테이션에 따라 내용이 조금 바뀌어있던데 이건 왜그런것일까?
  • @Builder는 RetentionPolicy가 SOURCE이고 retentionPolicy라는게 그냥 애노테이션의 life cycle이여서
    SOURCE면 .java까지만 남아있다. getter setter ... 이런애들도 전부 SOURCE여서 컴파일 된 이후에는 사라지고 바이트코드로 생성되죠 -> 즉, 애노테이션의 라이프사이클 설정중 java까지만 남아있는 것들은 컴파일 된 이후에는 해석되어 사라지고 코드로 추가된다는건가?
  • Lombok은 컴파일 시점에 바이트코드를 변환하여 원하는 부분을 주입해주는 방식으로 동작한다.

결과

  • = new ArrayList하는 부분이 builder에 대한 class에는 없기때문에

    (빌더 클래스에는 =new arrayList가 없음)
  • 필드에 정의해준것은 남아있지만 builder에는 없음

전체코드

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package jpaStudy.ex.entity;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;

@Entity
@NamedQuery(
    name = "Member.findByUsername",
    query = "select m from Member m where m.name = :name"
)
public class Member {
    @Id
    @GeneratedValue
    @Column(
        name = "MEMBER_ID"
    )
    private Long id;
    @Column
    private String name;
    private Integer age;
    @ElementCollection
    @CollectionTable(
        name = "Address",
        joinColumns = {@JoinColumn(
    name = "MEMBER_ID"
)}
    )
    private List<Address> addressList = new ArrayList();
    @ManyToOne(
        fetch = FetchType.EAGER
    )
    @JoinColumn(
        name = "team_id"
    )
    private Team team;
    @ManyToOne(
        fetch = FetchType.EAGER
    )
    @JoinColumn(
        name = "group1_id"
    )
    private Group1 group1;
    @Embedded
    private Address myAddress;

    public Member(String name, Team team) {
        this.name = name;
        team.addMember(this);
        this.team = team;
    }

    public Member(String name, Team team, int age, Group1 group1) {
        this.name = name;
        team.addMember(this);
        this.age = age;
        this.team = team;
        this.group1 = group1;
    }

    public static Member.MemberBuilder builder() {
        return new Member.MemberBuilder();
    }

    public Long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public Integer getAge() {
        return this.age;
    }

    public List<Address> getAddressList() {
        return this.addressList;
    }

    public Team getTeam() {
        return this.team;
    }

    public Group1 getGroup1() {
        return this.group1;
    }

    public Address getMyAddress() {
        return this.myAddress;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setAge(final Integer age) {
        this.age = age;
    }

    public void setAddressList(final List<Address> addressList) {
        this.addressList = addressList;
    }

    public void setTeam(final Team team) {
        this.team = team;
    }

    public void setGroup1(final Group1 group1) {
        this.group1 = group1;
    }

    public void setMyAddress(final Address myAddress) {
        this.myAddress = myAddress;
    }

    public Member() {
    }

    public Member(final Long id, final String name, final Integer age, final List<Address> addressList, final Team team, final Group1 group1, final Address myAddress) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.addressList = addressList;
        this.team = team;
        this.group1 = group1;
        this.myAddress = myAddress;
    }

    public static class MemberBuilder {
        private Long id;
        private String name;
        private Integer age;
        private List<Address> addressList;
        private Team team;
        private Group1 group1;
        private Address myAddress;

        MemberBuilder() {
        }

        public Member.MemberBuilder id(final Long id) {
            this.id = id;
            return this;
        }

        public Member.MemberBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public Member.MemberBuilder age(final Integer age) {
            this.age = age;
            return this;
        }

        public Member.MemberBuilder addressList(final List<Address> addressList) {
            this.addressList = addressList;
            return this;
        }

        public Member.MemberBuilder team(final Team team) {
            this.team = team;
            return this;
        }

        public Member.MemberBuilder group1(final Group1 group1) {
            this.group1 = group1;
            return this;
        }

        public Member.MemberBuilder myAddress(final Address myAddress) {
            this.myAddress = myAddress;
            return this;
        }

        public Member build() {
            return new Member(this.id, this.name, this.age, this.addressList, this.team, this.group1, this.myAddress);
        }

        public String toString() {
            return "Member.MemberBuilder(id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", addressList=" + this.addressList + ", team=" + this.team + ", group1=" + this.group1 + ", myAddress=" + this.myAddress + ")";
        }
    }
}

출처
https://applefarm.tistory.com/m/136

profile
안녕하세요!

0개의 댓글