▶ MemberService memberSave member->id:1003, name: 홍길동
▶원래는 데이터를 볼수없지만
롬북 이용해서 @Data해주면 데이터 볼수 있음
▶여기서 Member는 객체임 테이블아님 주의하기 ⭐
객체를 매핑한 member1테이블의 데이터가 select 되는것 ..!
<h1>JPA 회원조회</h1>
<div class="nav">
<form action="/members/search" method="post">
회원검색이름 : <input type="text" name="name" placeholder="회원검색 이름을 입력하세요">
<button type="submit">검색</button><p>
</form>
</div>
//이름으로 회원조회
@PostMapping(value = "members/search")
public String membersSearch(Member member, Model model) {
System.out.println("/members/search member.getName()-->"+member.getName());
List<Member> memberList = memberService.getListSearchMember(member.getName());
System.out.println("/members/search memberList.size()-->"+memberList.size());
model.addAttribute("members",memberList);
return "members/memberList";
}
public List<Member> getListSearchMember(String searchName) {
System.out.println("MemberService getListSearchMember start . . ." );
System.out.println("MemberService getListSearchMember SearchName-> " +searchName );
List<Member> listMember = memberRepository.findByNames(searchName);
System.out.println("MemberService getListSearchMember listMember.size()-> "+listMember.size());
return listMember;
}
package com.oracle.oBootJpa01.repository;
import java.util.List;
import com.oracle.oBootJpa01.domain.Member;
public interface MemberRepository {
Member memberSave(Member member); //멤버 저장
List<Member> findAllMember();
*********************추가****************
List<Member> findByNames(String searchName);
******************************************
}
//이름으로 회원조회
@Override
public List<Member> findByNames(String searchName) {
String pname = searchName + "%";
System.out.println("JpaMemberRepository findByNames pname-> "+pname);
List<Member> memberList = em.createQuery("select m from Member m where name Like : name", Member.class)
.setParameter("name", pname)
.getResultList()
;
System.out.println("JpaMemberRepository memberList.size ()-->"+memberList.size());
return memberList;
}
- JPA (Java Persistence API) 연관관계 방향
- 단방향 / 양방향.
- JPA (Java Persistence API) 연관관계 다중성
- 다대일(N:1), 일대다(1:N), 일대일(1:1), 다대다(N:M)
- JPA (Java Persistence API) 연관관계 Owner(주인)
- 객체 양방향 연관관계는 관리 Owner(주인) 필요
- 다대일(@ManyToOne)
- 일대다(@OneToMany)
- 일대일@OneToOne )
- 다대다(@ManyToMany)
▶ 다대다인거 사용 x 실무에서 거의 사용하지 않음
<body>
<a href="members/new">Member 신규 생성</a><p>
<a href="members">Member List 조회</a><p>
</body>
server.port=8384
#Oracle Connect
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xe
spring.datasource.username=scottjpa
spring.datasource.password=tiger
#Jpa Setting
spring.jpa.show-sql=true
#*** Operation - -> none
spring.jpa.hibernate.ddl-auto=create
과제
Entity
table->member2
Long id (pk설정)
String name
Long sal
Getter/Setter/ToString
시퀸스 설정
✔⭐Getter/Setter/ToString 는 @Data로 적어주면 한번에 설정됨
package com.oracle.oBootJpa02.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
@Entity
@Data
@SequenceGenerator(name = "member_seq_gen", //객체 SEQ
sequenceName = "member_seq_generator", // DB SEQ
initialValue = 1, //1부터 시작하고
allocationSize = 1 //1씩올라감
)
@Table(name="member2")
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE , // 전략 시퀸스 타입
generator = "member_seq_gen" //객체를 할당받아서
)
@Column(name = "member_id" , precision = 10) //id컬럼명을 member_id 10바이트로 줌
private Long id;
@Column(name = "username" , length = 50)
private String name;
private Long sal;
}
과제
Entity
table->Team
Long team_id (PK)
String name(column-->teamname)
Getter/Setter/ToString
1) 객체 SEQ team_seq_gen(PK에 할당)
2) DB SEQ team_seq_generator
package com.oracle.oBootJpa02.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Data
@SequenceGenerator(name = "member_seq_gen", //객체 SEQ
sequenceName = "team_seq_generator", // DB SEQ
initialValue = 1,//1부터 시작하고
allocationSize = 1 //1씩올라감
)
@Table(name = "Team")
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, // 전략 시퀸스 타입
generator = "team_seq_gen" //객체를 할당받아서
)
private Long team_id;
@Column(name = "teamname" ) //name컬럼명 이름
private String name;
private Long star;
//실제 Colunm x -->Buffer용도
@Transient
private String teamname;
}
▶여러사람들이 하나의 팀을 가지고 있다 .다대일
// 관계 설정
@ManyToOne //다대일 내가많고 팀이 하나 (팀이 아버지)
@JoinColumn(name = "team_id") //team_id 를가지고 조인한다
private Team team;
🔽 관계설정후 DB
<!DOCTYPE html>
<html xml:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Jpa회원등록2</h1>
<div class="container">
<form action="/memberSave" method="post">
<!-- ID :<input type="text" id="id" name="id" required="required"> -->
회원이름: <input type="text" id="name" name="name" placeholder="회원이름을 입력하세요"><p>
팀 이름 : <input type="text" id="name" name="teamname" placeholder="팀이름을 입력하세요">
<button type="submit">등록</button>
</form>
</div> <!-- container -->
</body>
</html>
index 로 이동
@Controller
public class MemberController {
private static final Logger logger = LoggerFactory.getLogger(MemberController.class);
private final MemberService memberService;
private MemberController ( MemberService memberService) {
this.memberService = memberService;
}
//화면이동
@GetMapping(value = "members/new") //index 로 이동
public String createForm() {
System.out.println("MemberController/members/save start . . . ");
return "members/createMemberForm";
}
//회원가입
//저장 수정 할때 -->post매핑
@PostMapping(value = "/memberSave")
public String memberSave(Member member) {
System.out.println("MemberController create start . . .");
System.out.println("member.getTeam() --> "+member.getTeam());
System.out.println("member.getName()->" +member.getName());
memberService.memberSave(member);
return "redirect:/";
}
package com.oracle.oBootJpa02.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.oracle.oBootJpa02.domain.Member;
import com.oracle.oBootJpa02.repository.MemberRepository;
@Service
@Transactional
public class MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
//회원가입
public Member memberSave(Member member) {
System.out.println("MemberService memberSave member->"+member);
memberRepository.memberSave(member);
return member;
}
}
인터페이스로 생성
package com.oracle.oBootJpa02.repository;
import com.oracle.oBootJpa02.domain.Member;
public interface MemberRepository {
Member memberSave(Member member);
}
MemberRepository 상속받아서 생성
package com.oracle.oBootJpa02.repository;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.oracle.oBootJpa02.domain.Member;
import com.oracle.oBootJpa02.domain.Team;
@Repository
public class JpaMemberRepository implements MemberRepository {
private final EntityManager em;
@Autowired
public JpaMemberRepository(EntityManager em) {
this.em = em;
}
@Override
public Member memberSave(Member member) {
// 팀저장
Team team = new Team();
team.setName(member.getTeamname());
em.persist(team);
//회원저장
member.setTeam(team); //팀객체를 통채로 넣을수 있다 .
em.persist(member);
return member;
}
}
//회원조회
@GetMapping(value = "/members")
public String listMember(Model model) {
List<Member> memberList = memberService.getListAllMember();
logger.info("members", memberList);
model.addAttribute("members" ,memberList);
return "members/memberList";
}
//회원조회
public List<Member> getListAllMember() {
List<Member> listMember = memberRepository.findAll();
System.out.println("MemberService getListAllMember listMember.size()-->"+listMember.size());
return listMember;
}
List<Member> findAll();
@Override
public List<Member> findAll() {
List<Member> memberList = em.createQuery("select m from Member m", Member.class)
.getResultList();
System.out.println("JpaMemberRepository findAll memberList.size()->"+memberList.size());
return memberList;
}
<!DOCTYPE html>
<html xml:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>회원수정</h1>
<div class="container">
<form action="/members/memberUpdate" method="post">
<!-- ID :<input type="text" id="id" name="id" required="required"> -->
<input type="hidden" name="name" th:value="${member.id}"><p>
<input type="hidden" name="teamid" th:value="${member.team.team_id}">
회원이름: <input type="text" id="name" name="name" th:value="${member.id}"><p>
팀 이름 : <input type="text" id="name" name="teamname" th:value="${member.team.name}">
<button type="submit">회원 수정 처리</button>
</form>
</div> <!-- container -->
</body>
</html>
//회원수정
@GetMapping(value="/memberModifyForm")
public String memberModify(Long id, Model model) {
System.out.println("MemberController memberModify id -> "+id);
Member member =memberService.findByMember(id);
System.out.println("member.get().getId()->"+member.getId());
System.out.println("member.get().getName()->"+member.getName());
System.out.println("member.get().getTeam()->"+member.getTeam());
model.addAttribute("member", member);
return "members/memberModify";
}
//회원수정
public Member findByMember(Long memberId) {
Member member1 = memberRepository.findByMember(memberId);
return member1;
}
Member findByMember(Long memberId);
@Override
public List<Member> findAll() {
List<Member> memberList = em.createQuery("select m from Member m", Member.class)
.getResultList();
System.out.println("JpaMemberRepository findAll memberList.size()->"+memberList.size());
return memberList;
}
@Override
public Member findByMember(Long memberId) {
Member member = em.find(Member.class, memberId);
return member;
}
//회원 수정업데이트
@PostMapping("/members/memberUpdate")
public String memberUpdate(Member member, Model model ) {
System.out.println("MemberController memberUpdate getid -> " +member.getId());
System.out.println("MemberController memberUpdate member.getName()->"+member.getName());
System.out.println("MemberController memberUpdate member.getTeamname()->"+member.getTeamname());
memberService.memberUpdate(member);
return "redirect:/members";
}
//회원수정저장
public void memberUpdate(Member member) {
System.out.println("MemberService memberUpdate member.getName()->"+member.getName());
System.out.println("MemberService memberUpdate member.getTeamname()->"+member.getTeamname());
memberRepository.updateByMember(member);
return ;
}
//회원수정
Member findByMember(Long memberId);
int updateByMember(Member member);
//회원수정업데이트
@Override
public int updateByMember(Member member) {
int result = 0 ; //수정결과를 0으로 해줌
System.out.println("JpaMemberRepository updateByMember member.getId() -> " +member.getId());
Member member3 = em.find(Member.class, member.getId()); //멤버저장해서 id꺼내옴
if(member3 != null) {
//팀 저장
System.out.println("JpaMemberRepository updateByMember member.getTeamid() ->"+member.getTeamid() );
Team team = em.find(Team.class ,member.getTeamid());
if(team != null) {
System.out.println("JpaMemberRepository updateByMember member.getTeamname() -> " +member.getTeamname());
team.setName(member.getTeamname());
em.persist(team);
//회원저장
System.out.println("JpaMemberRepository updateByMember member.getname() -> " +member.getName());
member3.setTeam(team);
member3.setName(member.getName());
em.persist(member3);
result =1;
} else {
result=0;
System.out.println(" JpaMemberRepository updateByMember No Exist. . . ");
}
}
return result;
}