MemberRepository를 인터페이스(상속) 해서 만듬
package com.oracle.oBootDBConnect.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Repository;
import com.oracle.oBootDBConnect.domain.Member1;
@Repository
public class JdbcMemberRepository implements MemberRepository {
//JDBC사용
private final DataSource dataSource;
public JdbcMemberRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
//회원가입
@Override
public Member1 save(Member1 member1) {
String sql = "insert into member1(id,name) values(member_seq.nextval,?)";
System.out.println("JdbcMemberRepository sql-> "+sql);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, member1.getName());
pstmt.executeUpdate();
System.out.println("JdbcMemberRepository pstmt.executeUpdate After");
return member1;
} catch (Exception e) {
throw new IllegalStateException(e);
}finally {
close(conn, pstmt, rs );
}
}
private void close(Connection conn) throws SQLException {
DataSourceUtils.releaseConnection(conn, dataSource);
// TODO Auto-generated method stub
}
-----------------------------------------
//목록 조회
@Override
public List<Member1> findAll() {
// TODO Auto-generated method stub
return null;
}
--------------------------------------------
//finally에서
//close하는 게 try catch로 너무 많고 지저분해서 따로빼주기 .
private void close(Connection conn , PreparedStatement pstmt, ResultSet rs) {
try {
if(rs != null) rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(pstmt != null) pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(conn != null) close( conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JdbcMemberRepository에 @Repository 써줫기때문에 쓰면 안됨 .
@Repository는 두개 걸면 안됨
//@Repository //저장소 -->JdbcMemberRepository에 @Repository 써줫기때문에 쓰면 안댐 .
public class MemoryMemberRepository implements MemberRepository {
private static Map<Long, Member1> store = new HashMap<>();
private static long sequence = 0L;
옜날에는 해줘야했지만 현재 버전 올라가서 안해줘도 가능함
DateSource를 가져와서 쓰기
package com.oracle.oBootDBConnect;
import javax.sql.DataSource;
import org.springframework.context.annotation.Configuration;
@Configuration //bean으로 설정
public class SpringConfig {
private final DataSource dataSource;
public SpringConfig(DataSource dataSource) {
this.dataSource = dataSource;
}
}
▶목록은 조회 되지 않고 DB에 입력만 되어짐
//목록 조회
@Override
public List<Member1> findAll() {
String sql = "select * from member1";
System.out.println("findAll sql-> "+sql);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<Member1> members = new ArrayList<>();
while (rs.next()) {
Member1 member = new Member1();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
members.add(member);
}
return members;
} catch (Exception e) {
throw new IllegalStateException(e);
}finally {
close(conn, pstmt, rs );
}
}
package com.oracle.oBootDBConnect.repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.oracle.oBootDBConnect.domain.Member1;
//@Repository //저장소 -->JdbcMemberRepository에 @Repository 써줫기때문에 쓰면 안댐 .
public class MemoryMemberRepository implements MemberRepository {
private static Map<Long, Member1> store = new HashMap<>();
private static long sequence = 0L;
@Override
public Member1 save(Member1 member1) {
System.out.println("MemoryMemberRepository save start . . . ");
member1.setId(++sequence);
store.put(member1.getId(), member1);
return member1;
}
@Override public List<Member1> findAll() {
System.out.println("MemoryMemberRepository findAll Start . . . ");
//store의value(Member1)
List<Member1> listMember = new ArrayList<>(store.values());
//ArrayList에 value값만 가지고오면 list로 변환
System.out.println("MemoryMemberRepository findAll listMember.size() -> "+ listMember.size());
return listMember;
}
}
위에 jdbcMemberRepository.java/MemoryMemberRepository에서
@Repository 모두 없을시
//db랑 연결
@Bean
public MemberRepository memberRepository() {
//return new JdbcMemberRepository(dataSource); //DB랑 연결
return new MemoryMemberRepository(); //메모리
}
🔽DB랑 연결되어있을경우 DB에 입력되어있던 회원목록이 조회가 됨.
🔽메모리랑 연결되어 있을경우 DB에 입력되어있던것은 조회되지않고 등록한것들만 조회됨 .
▶Loombok->spring으로 복사해놓기
▶cmd실행
▶Lombok 설정 완료
▶롬북설치 --> Build.gradle 코드 리프레쉬
OOP 프로그래밍시 설계할 클래스들과 데이터저장소로 이용될 RDBMS의 Table 간의 Mapping
1) myBatis
2) Hibernate
🔽Member은 테이블이아니라 객체이다 //member1이 member객체를 매핑 member1이 테이블⭐
.JPA(Java Persistence API)
- 자바 진영의 ORM 기술 표준
- Java Program(일반적으로 DAO) 에서 JPA에 접근 (Entit
- SQL 중심적인 개발에서
객체 중심으로 개발- 생산성
- 유지보수
- 성능
- 데이터 접근 추상화와
벤더 독립성- 표준
1) 저장: jpa.persist(emp)
2) 조회: Emp emp= jpa.find(empno)
3) 수정: emp.setEname(“변경할 이름”)
4) 삭제: jpa.remove(emp
server.port=8383
#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
spring.jpa.hibernate.ddl-auto=create
▶개발끝나면 create --> none으로 바꿔야함
createㅎ ㅐ놓으면 실행할때마다 테이블 새로 생성됨
none해놓으면 데이터 그대로
jpa에서는 pk키 지정해줘야한다 -->@id
package com.oracle.oBootJpa01.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;
@Entity //JPA에서 관리하는 DB작업 연동시켜줌
@Getter
@Setter
public class Member { //member은 테이블이 아니라 객체이다
@Id //pk키
private Long id;
private String name;
}
🔼 ⭐member은 테이블이 아니라 객체이다
<body>
<a href="members/new">Member 신규 생성</a><p>
<a href="members">Member List 조회</a><p>
</body>
인터페이스로 생성
package com.oracle.oBootJpa01.repository;
import com.oracle.oBootJpa01.domain.Member;
public interface MemberRepository {
Member memberSave(Member member); //멤버 저장
}
MemberRepository인터페이스 상속 받아 생성
package com.oracle.oBootJpa01.repository;
import javax.persistence.EntityManager;
import com.oracle.oBootJpa01.domain.Member;
@Repository
public class JpaMemberRepository implements MemberRepository {
//JPA DML --> EntityManager 필수
private final EntityManager em; //파이널로 하면 EM이 생성자로 들어가야함
//SETTER안만들고 절대 바꾸면 안됨
public JpaMemberRepository(EntityManager em) {
this.em = em; //나의 em하고 연결시킨다
}
@Override
public Member memberSave(Member member) {
//저장메소드
em.persist(member);
System.out.println("JpaMemberRepository memberSave member After. . .");
return member;
}
}
package com.oracle.oBootJpa01.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.oracle.oBootJpa01.repository.MemberRepository;
@Service
public class MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
}
package com.oracle.oBootJpa01.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.oracle.oBootJpa01.domain.Member;
import com.oracle.oBootJpa01.repository.MemberRepository;
@Service
@Transactional
public class MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
// 회원가입
public Long memberSave(Member member) {
System.out.println("MemberService memberSave member->"+member);
memberRepository.memberSave(member);
return member.getId();
}
}
-->JpaMemberRepository.java에 @Repository 등록
package com.oracle.oBootJpa01.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.oracle.oBootJpa01.domain.Member;
import com.oracle.oBootJpa01.service.MemberService;
@Controller
public class MemberController {
private final MemberService memberService;
private static final Logger logger = LoggerFactory.getLogger(MemberController.class);
@Autowired
private MemberController(MemberService memberService) { //생성자 주입
this.memberService = memberService; //나의 멤버서비스에 등록
}
//조회할떄 --->get매핑
@GetMapping(value="/members/new")
public String createFrom() {
System.out.println("MemberController/members/new start. . . ");
return "members/createFrom";
}
//저장 수정 할때 -->post매핑
@PostMapping(value = "members/save")
public String memberSave(Member member) {
System.out.println("MemberController memberSave start . . .");
System.out.println("member.getId() --> "+member.getId());
System.out.println("member.getName()->" +member.getName());
memberService.memberSave(member);
return "redirect:/";
}
}
🔽실행
🔽DB에 테이블이 생성됨 .
🔽localhost:8383 실행 (member 신규생성하면 DB에도 입력되어짐
//회원 조회
//조회할떄 --->get매핑
@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.findAllMember();
System.out.println("MemberService getListAllMember 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();
}
⭐createQuery("select m from Member m", Member.class)
-->sql아님 객체(Member) 를 가져오는거임
public List<Member>findAllMember() {
List<Member> memberList = em.createQuery("select m from Member m", Member.class)
.getResultList();
System.out.println("JpaMemberRepository findAllMember 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>
<div class="container">
<div>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>이름</th>
</tr>
</thead>
<tbody>
<tr th:each="member : ${members}">
<td th:text="${member.id}"></td>
<td th:text="${member.name}"></td>
</tr>
</tbody>
</table>
</div>
</div> <!-- container -->
</body>
</html>
🔽실행결과