[TIL] 20250304

김민석·2025년 3월 4일
post-thumbnail

오늘 목표

  • 수업 전 운동하기(O)
  • 수업 후 모르는 내용 정리 및 복습(O)
  • js프로젝트에 적용해보기(O)
  • 알고리즘 문제 풀기(O)

배운 내용

sql 기본문법

-- customers 테이블에서 country(국가)를 중복 제거한 후 개수를 구함
SELECT COUNT(DISTINCT country) FROM customers; 

-- 이중 쿼리를 사용하여 country를 중복 제거한 후 개수를 구함
SELECT COUNT(*) AS distinctan 
FROM (SELECT DISTINCT country FROM customers) c; 

-- country가 'Mexico'인 고객 정보를 조회
SELECT * FROM customers WHERE country = 'Mexico';  

-- products 테이블을 price 기준으로 오름차순 정렬하여 조회
SELECT * FROM products ORDER BY price;  

-- products 테이블을 price 기준으로 내림차순 정렬하여 조회
SELECT * FROM products ORDER BY price DESC;  

-- customers 테이블을 pric오름차순 정렬 후 customername 내림차순 정렬하여 조회
SELECT * FROM customers ORDER BY price ASC, CustomerName DESC;  

-- 고객 이름이 'A'로 시작하는 고객 정보를 조회
SELECT * FROM customers WHERE customername LIKE 'A%';  

-- city(도시) 값이 'L_nd__' 패턴과 일치하는 고객 정보 조회
-- 언더바(_)는 한 글자를 의미하며, 예를 들어 'London'이 매칭될 수 있음
SELECT * FROM customers WHERE city LIKE 'L_nd__';  

-- 고객 이름에 'a'가 포함된 고객 정보를 조회
SELECT * FROM customers WHERE customername LIKE '%a%';   

-- 고객 이름이 'z'로 끝나는 고객 정보를 조회
SELECT * FROM customers WHERE customername LIKE '%z';  

-- customers 테이블에서 처음 10개의 행만 조회
SELECT * FROM customers LIMIT 10;  

-- 각 categoryId별로 가장 낮은 price를 조회
SELECT MIN(price) AS smallprice, categoryId 
FROM products 
GROUP BY categoryId;  

-- orders 테이블과 customers 테이블을 customerid 기준으로 내부 조인
-- 주문 ID(orderid), 주문 날짜(orderdate), 고객 ID(orders.customerid), 고객 이름(customername) 조회
SELECT orderid, orderdate, orders.customerid, customername 
FROM orders 
INNER JOIN customers ON orders.customerid = customers.customerid;	

-- table에 product가 있을 시 삭제
drop table if exists product;

-- 
//데이터데이브 설정
use ureca;
//변경된 내용을 모두 영구 저장한다. COMMIT 수행하면, 하나의 트랜젝션 과정을 종료하게 된다.
commit;

MySQL과 Spring Boot + JDBC를 활용하여 상품 정보를 조회

DTO (Data Transfer Object): Product.java

  • Product 객체를 정의하는 클래스
  • 상품 데이터를 저장하고 주고받는 역할을 담당
package com.shop.cafe.dto;

public class Product {
    private int procode, price;
    private String prodname, pimg;

    // 생성자 (모든 필드 초기화)
    public Product(int procode, String prodname, int price, String pimg) {
        super();
        this.procode = procode;
        this.price = price;
        this.prodname = prodname;
        this.pimg = pimg;
    }

    // toString 메서드 (객체 정보를 문자열로 변환)
    @Override
    public String toString() {
        return "Product [procode=" + procode + ", price=" + price + ", prodname=" + prodname + ", pimg=" + pimg + "]";
    }

    // 기본 생성자 (빈 객체 생성 가능)
    public Product() {
        super();
    }

    // Getter & Setter 메서드 (데이터 접근 및 수정)
    public int getProcode() {
        return procode;
    }
    public void setProcode(int procode) {
        this.procode = procode;
    }

    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }

    public String getProdname() {
        return prodname;
    }
    public void setProdname(String prodname) {
        this.prodname = prodname;
    }

    public String getPimg() {
        return pimg;
    }
    public void setPimg(String pimg) {
        this.pimg = pimg;
    }
}

DAO (Data Access Object) - ProductDao.java

  • 데이터베이스(MySQL)에서 상품 정보를 조회하는 클래스
  • JDBC를 사용하여 직접 DB 연결 및 쿼리 실행
package com.shop.cafe.dao;

import java.sql.*;
import java.util.*;

import org.springframework.stereotype.Component;
import com.shop.cafe.dto.Product;

@Component  // Spring이 이 클래스를 자동으로 관리하게 함 
public class ProductDao {

    // 상품 전체 조회 메서드
    public List<Product> getAllProducts() throws Exception {
        // 1. MySQL JDBC 드라이버 로드
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 2. 데이터베이스 연결 정보 설정
        String url = "jdbc:mysql://localhost:3306/ureca?serverTimezone=UTC";
        String user = "ureca";
        String pw = "ureca";

        // 3. 실행할 SQL 쿼리
        String sql = "SELECT * FROM product";

        // 4. try-with-resources (자동 자원 해제)
        try (
            Connection con = DriverManager.getConnection(url, user, pw); // DB 연결
            PreparedStatement stmt = con.prepareStatement(sql);  // SQL 실행 준비
            ResultSet rs = stmt.executeQuery(); // SQL 실행 및 결과 저장
        ) {
            List<Product> list = new ArrayList<>();

            // 5. 결과(ResultSet) 반복 조회
            while (rs.next()) {
                int prodcode = rs.getInt("prodcode");
                String prodname = rs.getString("prodname");
                String pimg = rs.getString("pimg");
                int price = rs.getInt("price");

                // Product 객체 생성 후 리스트에 추가
                list.add(new Product(prodcode, prodname, price, pimg));
            }
            return list;  // 상품 리스트 반환
        }
    }
}

Service - ProductService.java

  • DAO를 호출하여 데이터를 가져오는 비즈니스 로직을 수행
  • Controller와 DAO 사이에서 중간 역할
package com.shop.cafe.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shop.cafe.dao.ProductDao;
import com.shop.cafe.dto.Product;

@Service  // Spring이 관리하는 서비스 클래스임을 명시
public class ProductService {

    @Autowired
    ProductDao productDao;  // ProductDao 주입

    // 상품 전체 조회
    public List<Product> getAllProducts() throws Exception {
        return productDao.getAllProducts();
    }
}

Controller (API 제공) - ProductController.java

  • HTTP 요청을 받아 Service를 호출하여 결과를 반환
  • 클라이언트(프론트엔드)가 API를 통해 상품 데이터를 요청할 수 있도록 함
package com.shop.cafe.controller;

import org.springframework.web.bind.annotation.RestController;
import com.shop.cafe.dto.Product;
import com.shop.cafe.service.ProductService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

@RestController  // REST API 컨트롤러 선언
@CrossOrigin("http://localhost:5500/")  // CORS 문제 해결 (프론트엔드에서 접근 허용)
public class ProductController {

    @Autowired  // Service 주입
    ProductService productService;

    // 모든 상품 조회 API
    @GetMapping("getAllProducts")
    public List<Product> getAllProducts() {
        try {
            System.out.println("getProducts");
            return productService.getAllProducts();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

CORS(Cross-Origin Resource Sharing)란?

CORS(Cross-Origin Resource Sharing)는 웹 브라우저에서 보안 정책으로 인해 서로 다른 도메인(origin)에서 리소스를 요청할 때 발생하는 보안 메커니즘입니다.

CORS의 발생이유?

CORS 오류는 클라이언트(프론트엔드)와 서버(백엔드)의 출처가 다를 때 발생합니다.
예를 들어, 프론트엔드가 http://localhost:5500에서 실행되고, 백엔드가 http://localhost:8080에서 실행된다면,
fetch 또는 Axios 같은 HTTP 요청을 보낼 때 브라우저에서 CORS 정책을 위반했다고 차단할 수 있습니다.

profile
나만의 기록장

0개의 댓글