반응형

#김영한 #스프링 #Spring #인프런 #인프런수업


본 포스팅은김영한선생님의
스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB접근 기술
강의를 기반으로 작성되었습니다.

 

 

 

 

 

 

회원 목록 조회 구현

  • controller/MemberController에 메서드를 추가한다
@GetMapping("/members")  
public String list(Model model){  
    // 모든 회원 가입된 정보를 가져온다  
    List<Member> members = memberService.findMembers();  
    // 멤버리스트를 모델에 모두다 대입하고 화면에 넘기는 것  
    model.addAttribute("members", members);  
    return "members/memberList";  
}
  • templates 패키지에 memberList,html 코드를 작성
<!DOCTYPE HTML>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
    <meta  http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
</head>  
<body>  
<div class="container">  
   <div>  
       <table>  
           <thead>  
           <tr>  
               <th> # </th>  
               <th> 이름 </th>  
           </tr>  
           </thead>  
           <tbody>           
      <!-- th:each 는 타임리프의 문법이고 반복문을 돌면서 진행한다-->  
           <tr th:each="member: ${members}">  
               <td th:text="${member.id}"></td>  
               <td th:text="${member.name}"></td>  
           </tr>  
           </tbody>  
       </table>  
   </div>  
</div>  
</body>  
</html>

💡 참고 💡
현재 구조에서는 DB를 활용하지 않았으므로 자바를 껏다 키면 저장된 데이터가 모두 날라간다
그러므로 DB를 연동하는 작업을 해야한다

 

 

 

DB 접근

H2 데이터 베이스 설치
순수 jdbc
스프링 jdbcTemplate
JPA
스프링 데이터 JPA

 

 

 

 

H2 데이터 베이스 설치

설치는 어렵지 않기 때문에 강의 참고

SQL쿼리문

drop table if exists member CASCADE;   
create table member(  
    id bigint generated by default as identity,    name varchar(255),    primary key(id)  
)
insert into member(name) values('spring')

 

순수JDBC 연결 by.정신에 해롭다

자바는 DB랑 연결할 경우 JDBC 파일이 꼭 필요하다
DB에 붙을 때 클라이언트 라이브러리도 필요하다

build.gradle 파일에 jdbc, h2 데이터베이스 관련 라이브러리 추가

 

 implementation 'org.springframework.boot:spring-boot-starter-jdbc'
 runtimeOnly 'com.h2database:h2'

 

스프링 부트 데이터베이스 연결 설정 추가

resources/application.properties

 spring.datasource.url=jdbc:h2:tcp://localhost/~/test
 spring.datasource.driver-class-name=org.h2.Driver
 spring.datasource.username=sa

CRUD 작업은 기존에 JAVA문법과 동일하다
차이점은 데이터베이스에 커넥션을 가져올때 트랜잭션에 문제가 될 수 있기 때문에
스프링을 통해서 가져오는 작업을 해야한다

리소스 반납할때도 DataSourceUtils를 사용하여 반납한다 

private Connection getConnection(){
	return DataSourceUtils.getConnection(dataSource);
}

DataSource는 데이터베이스 커넥션을 획득할 때 사용하는 객체다. 스프링 부트는 데이터베이스 커넥션 정보를 바탕으로 DataSource를 생성하고 스프링 빈으로 만들어둔다. 그래서 DI를 받을 수 있다.

 

 

 

스프링에 장점

  • 개방-폐쇄 원칙 준수(OCP , Open-Closed Principle)
    확장에는 열려있고 수정, 변경에는 닫혀있다
  • 스프링의 DI를 사용하면 기존 코드를 전혀 손대지 않고 설정만으로 구현 클래스를 변경 할 수 있다
반응형
유리쯔의일상