Skip to content

Commit

Permalink
Merge pull request #38 from ahyoon99/dev/connectDB/#37
Browse files Browse the repository at this point in the history
Dev/connect db/#37
  • Loading branch information
ahyoon99 authored Aug 20, 2024
2 parents f862f7a + a415036 commit 2f3f067
Show file tree
Hide file tree
Showing 7 changed files with 134 additions and 3 deletions.
6 changes: 6 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ dependencies {

// https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' // swagger

// jdbc 라이브러리
implementation 'org.springframework.boot:spring-boot-starter-jdbc'

// h2 DB 라이브러리
runtimeOnly 'com.h2database:h2'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public class ApiController {

private final WishListService wishListService;

@GetMapping("/findById")
public WishListDto findById(@RequestParam int index){
return wishListService.findById(index);
}

@GetMapping("/search")
public WishListDto search(@RequestParam String query){
return wishListService.search(query);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.example.naverrestaurant.db;

import com.example.naverrestaurant.wishlist.entity.WishListEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.util.List;
import java.util.Optional;



abstract public class H2DbRepositoryAbstract<T extends MemoryDbEntity> implements MemoryDbRepositoryIfs<T>{
private JdbcTemplate jdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource){
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

@Override
public Optional<T> findById(int index) {
String findByIdQuery = "select * from restaurant where index=? limit 1";
int findByIdParam = index;

WishListEntity wishListEntity = jdbcTemplate.queryForObject(findByIdQuery,
wishListEntityRowMapper(),
index);

return (Optional<T>) Optional.of(wishListEntity);
}

@Override
public T save(T entity) {
String saveQuery = "insert into " +
"restaurant(title, category, address, roadAddress, homepageLink, imageLink, isvisit, visitCount, lastVisitDate) " +
"values (?,?,?,?,?,?,?,?,?)";
WishListEntity wishListEntity = (WishListEntity) entity;

Object []saveParams = new Object[] {wishListEntity.getTitle(),
wishListEntity.getCategory(), wishListEntity.getAddress(), wishListEntity.getRoadAddress(),
wishListEntity.getHomePageLink(), wishListEntity.getImageLink(), wishListEntity.isVisit(),
wishListEntity.getVisitCount(), wishListEntity.getLastVisitDate() };

jdbcTemplate.update(saveQuery, saveParams);

String lastInsertIndexQuery = "select max(index) from restaurant";
int listInsertIndex = jdbcTemplate.queryForObject(lastInsertIndexQuery, int.class);

String lastInsertEntityQuery = "select * from restaurant where index=?";
WishListEntity result = jdbcTemplate.queryForObject(lastInsertEntityQuery, wishListEntityRowMapper(), listInsertIndex);
return (T) result;
}

@Override
public void deleteById(int index) {
String deleteByIdQuery = "delete from restaurant where index=?";
int deleteByIdParam = index;
int result = this.jdbcTemplate.update(deleteByIdQuery, deleteByIdParam);
System.out.println("delete : "+result);
}

@Override
public List<T> listAll() {
String listAllQuery = "select * from restaurant";
List<WishListEntity> result = this.jdbcTemplate.query(listAllQuery, wishListEntityRowMapper());
return (List<T>) result;
}

private RowMapper<WishListEntity> wishListEntityRowMapper(){
return ((rs, rowNum) -> {
WishListEntity wishListEntity = new WishListEntity();
wishListEntity.setIndex(rs.getInt("index"));
wishListEntity.setTitle(rs.getString("title"));
wishListEntity.setCategory(rs.getString("category"));
wishListEntity.setAddress(rs.getString("address"));
wishListEntity.setRoadAddress(rs.getString("roadAddress"));
wishListEntity.setHomePageLink(rs.getString("homePageLink"));
wishListEntity.setImageLink(rs.getString("imageLink"));
wishListEntity.setVisit(rs.getBoolean("isVisit"));
wishListEntity.setVisitCount(rs.getInt("visitCount"));
if(rs.getTimestamp("lastVisitDate") != null){ // lastVisitDate가 null이 아닐 때만 set 해주기
wishListEntity.setLastVisitDate(rs.getTimestamp("lastVisitDate").toLocalDateTime());
}
return wishListEntity;
});
}

}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.example.naverrestaurant.wishlist.repository;

import com.example.naverrestaurant.db.H2DbRepositoryAbstract;
import com.example.naverrestaurant.db.MemoryDbRepositoryAbstract;
import com.example.naverrestaurant.db.MemoryDbRepositoryIfs;
import com.example.naverrestaurant.wishlist.entity.WishListEntity;
import org.springframework.stereotype.Repository;

@Repository
public class WishListRepository extends MemoryDbRepositoryAbstract<WishListEntity> {
public class WishListRepository extends H2DbRepositoryAbstract<WishListEntity> {
}
//public class WishListRepository extends MemoryDbRepositoryAbstract<WishListEntity> {
//}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.example.naverrestaurant.wishlist.service;

import com.example.naverrestaurant.db.MemoryDbEntity;
import com.example.naverrestaurant.naver.NaverClient;
import com.example.naverrestaurant.naver.dto.SearchImageReq;
import com.example.naverrestaurant.naver.dto.SearchLocalReq;
Expand All @@ -11,6 +10,7 @@
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
Expand Down Expand Up @@ -98,6 +98,14 @@ public void delete(int index) {
wishListRepository.deleteById(index);
}

public WishListDto findById(int index) {
Optional<WishListEntity> wishListEntity = wishListRepository.findById(index);
if(!wishListEntity.isPresent()){ // wishListEntity에 값이 없으면 Exception 처리하기
throw new IllegalArgumentException();
}
return entityToDto(wishListEntity.get()); // wishListEntity에 값이 있으면 wishListDto로 변환하여 리턴하기
}

public void addVisit(int index) {
var restaurant = wishListRepository.findById(index);
if (restaurant.isPresent()){
Expand All @@ -106,4 +114,5 @@ public void addVisit(int index) {
restaurnatEntity.setVisitCount(restaurnatEntity.getVisitCount()+1);
}
}

}
2 changes: 2 additions & 0 deletions src/main/resources/h2/data.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
insert into RESTAURANT(title, category, address, roadAddress, homepageLink, imageLink, isVisit, visitCount, lastVisitDate) VALUES ('전주 마라탕2', '중식', '전주시 만성동1', '만성로1', 'www.maratang.com', 'www.pic1.jpeg',FALSE,0,'2023-08-10 11:28:36.026095');
insert into RESTAURANT(title, category, address, roadAddress, homepageLink, imageLink, isVisit, visitCount, lastVisitDate) VALUES ('만성 찜닭2', '한식', '전주시 만성동2', '만성로2', 'www.zzimdak.com', 'www.pic2.jpeg',TRUE,0,'2024-08-12 11:28:36.026095');
16 changes: 16 additions & 0 deletions src/main/resources/h2/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
DROP TABLE IF EXISTS RESTAURANT;

-- 식당
CREATE TABLE RESTAURANT
(
index INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL, -- 가게명, 음식명
category VARCHAR(255) NOT NULL, -- 카테고리
address VARCHAR(255) NOT NULL, -- 주소
roadAddress VARCHAR(255), -- 도로명 주소
homePageLink VARCHAR(255), -- 홈페이지 주소
imageLink VARCHAR(255), -- 음식, 가게 이미지 주소
isVisit BOOLEAN NOT NULL, -- 방문 여부
visitCount INTEGER NOT NULL, -- 방문 횟수
lastVisitDate TIMESTAMP -- 마지막 방문 날짜
);

0 comments on commit 2f3f067

Please sign in to comment.