source 는 Github 에 있습니다.
@Service
public class Test {
@Transactional
public xxx xxx(...) {
xxxUpdate(...);
xxxInsert(...);
xxxDelete(...);
}
}
application.yml
spring:
jpa:
open-in-view: false
@Entity
@Getter
@NoArgsConstructor
public class Member {
@Id
@GeneratedValue
@Column(name = "member_id")
private Long id;
@Column
private String name;
@Column
private String telNo;
@Column
private int age;
@JsonIgnore
@OneToMany(mappedBy = "member")
private List<Account> accounts = new ArrayList<>();
@Builder
public Member(Long id, String name, String telNo, int age) {
this.id = id;
this.name = name;
this.telNo = telNo;
this.age = age;
}
}
@Entity
@Getter
@NoArgsConstructor
public class Account {
@Id
@GeneratedValue
@Column(name = "account_id")
private Long id;
@Column
private String accountNo; // 계좌번호
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;
@Builder
public Account(String accountNo, Member member) {
this.accountNo = accountNo;
setMember(member);
}
public void setMember(Member member) {
this.member = member;
member.getAccounts().add(this);
}
}
@Slf4j
@RequiredArgsConstructor
@RestController
public class MemberApiController {
private final MemberService memberService;
/**
* osiv 테스트 api
* osiv 옵션이 꺼져있으면 account 가져올 때 에러남.
* MemberService 의 @Transaction 이 종료된 순간 영속성 컨텍스트가 종료되기에.
* @return
*/
@GetMapping("/api/training1/members")
public List<Member> getMembers1() {
List<Member> list = memberService.getMembers();
list.forEach(member -> {
log.info("account.size : {}", member.getAccounts().size());
});
return list;
}
}
@Slf4j
@RequiredArgsConstructor
@Service
public class MemberService {
private final MemberRepository memberRepository;
@Transactional(readOnly = true)
public List<Member> getMembers() {
return memberRepository.findAll();
}
}
@Service
@RequiredArgsConstructor
public class MemberCommandService {
private final MemberRepository memberRepository;
public Long saveMember(Member member) {
Member result = member.save(member);
return result.getId();
}
}
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class MemberQueryService {
private final MemberRepository memberRepository;
public List<Member> getMembers() {
return memberRepository.findAll();
}
}