기록해! 정리해!

JPAJarThymeleaf-2 (단방향 연관관계 매핑) 본문

SpringBoot

JPAJarThymeleaf-2 (단방향 연관관계 매핑)

zsuling 2022. 10. 20. 12:36

책 297p. 

 

게시판 : 번호, 제목, 내용

회원: 작성자, 지역

 

단방향 -> 게시판에서는 회원의 정보를 볼 수 있지만 

                회원이 작성한 글은 확인할 수 없다

양방향 -> 가능 (회원객체도 게시판객체를 참조해야한다. (조인))

 
다대일 연관 매핑을 테스트하기 위해서 다음과 같은 조건을 가정한다.
1. 게시판과 회원이 있다.
2. 한명의 회원은 여러개의 게시글은 작성할 수있다.
3. 게시판과 회원은 다대일 관계이다. ( N : 1 )
4. 게시글을 통해서 게시글을 작성한 회원 정보를 조회할 수 있다.
( 반대는 안된다. : 즉 회원이 작성한 글을 조회할 수는 없다. )

 

1. Member

package com.rubypaper.board;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table(name="Member1019")
public class Member {

	@Id
	@Column(name="MEMBER_ID")
	private String id;
	private String password;
	private String name;
	private String role;
}

2. Board

package com.rubypaper.board;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import lombok.Data;


@Data
@Entity
@Table(name="board1019")
public class Board {

	@Id
	@GeneratedValue
	private  Long seq;  
	private  String  title;
	private  String  content;
	@Temporal(value=TemporalType.TIMESTAMP)
	private  Date  createDate;	
	private  Long  cnt;		
	
	@ManyToOne
	@JoinColumn(name="MEMBER_ID")
	private Member  member;
}

3. DynamicMemberRepository

package com.rubypaper.board;

import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.CrudRepository;

public interface DynamicMemberRepository 
         extends CrudRepository <Member, String>,
          QuerydslPredicateExecutor<Member>{

}

4. RelationMappingTest

package com.rubypaper.test;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.rubypaper.board.Board;
import com.rubypaper.board.DynamicBoardRepository;
import com.rubypaper.board.DynamicMemberRepository;
import com.rubypaper.board.Member;


@RunWith(SpringRunner.class)
@SpringBootTest
public class RelationMappingTest {
	@Autowired
	private DynamicBoardRepository  boardRepo;	
	
	@Autowired
	private DynamicMemberRepository  memberRepo;	
		
		
	@Test
	public  void  testRelationMapping() {	
	    
		Member member1 =new Member();
		member1.setId("member1");
		member1.setName("소금빵");
		member1.setPassword("member111");
		member1.setRole("User");
		memberRepo.save(member1);
		
		Member member2 =new Member();
		member2.setId("member2");
		member2.setName("앙버터");
		member2.setPassword("member222");
		member2.setRole("Admin");
		memberRepo.save(member2);
		
		for(int i =1; i <=3; i++) {
			Board board=new Board();
			board.setMember(member1);
			board.setTitle("소금빵이 등록한 게시글 " + i);
			board.setContent("소금빵이 등록한 게시글 내용 " +i);
			board.setCreateDate(new Date());
			board.setCnt(1L);
			boardRepo.save(board);
		}
	
		for(int i =1; i <=4; i++) {
			Board board=new Board();
			board.setMember(member2);
			board.setTitle("앙버터가 등록한 게시글 " + i);
			board.setContent("앙버터가 등록한 게시글 내용 " +i);
			board.setCreateDate(new Date());
			board.setCnt(2L);
			boardRepo.save(board);
		}
		
	
	}
}

>>


1. RelationMappingTest2

package com.rubypaper.test;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.rubypaper.board.Board;
import com.rubypaper.board.DynamicBoardRepository;
import com.rubypaper.board.DynamicMemberRepository;
import com.rubypaper.board.Member;


@RunWith(SpringRunner.class)
@SpringBootTest
public class RelationMappingTest2 {
	@Autowired
	private DynamicBoardRepository  boardRepo;	
	
	@Autowired
	private DynamicMemberRepository  memberRepo;	
		
		
	@Test
	public  void  testRelationMapping() {	
	    
	Board board = boardRepo.findById(3L).get();
	
	System.out.println(board);
	System.out.println("번호:"+board.getSeq());
	System.out.println("제목:"+board.getTitle());
	System.out.println("내용:"+board.getContent());
	System.out.println("작성자 ID:"+board.getMember().getId());
	System.out.println("작성자 이름:"+board.getMember().getName());
	System.out.println("작성자 권한:"+board.getMember().getRole());
	}
}

>> 게시판에서 Member의 값을 불러올 수 있다

* right outer join

2. Board 수정

@ManyToOne
	@JoinColumn(name="MEMBER_ID", nullable=false)
	private Member  member;

상호호출 꼬리를 끊어야한다.

 

1. Member 추가

1) @ToString(exclude="boardList")

2)

	@OneToMany(mappedBy="member", fetch=FetchType.EAGER)
	private List<Board> boardList = new ArrayList<Board>();

 

2. Board 추가 :@ToString(exclude="member")


1. Member 추가

:cascade=CascadeType.ALL

2. Board 추가 

: nullable=false 하면 inner join됨

package com.rubypaper.board;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import lombok.Data;


@Data
@Entity
@Table(name="board1019")
public class Board {

	@Id
	@GeneratedValue
	private  Long seq;  
	private  String  title;
	private  String  content;
	@Temporal(value=TemporalType.TIMESTAMP)
	private  Date  createDate;	
	private  Long  cnt;		
	
	@ManyToOne
	@JoinColumn(name="MEMBER_ID", nullable=false)
	private Member  member;
}
Comments