
스타터 라이브러리가 좀 적다

이전에는 컴포넌트 스캔으로 메모리를 올렸었습니다.
스프링부트는 @SpringBootApplication

WEB.XML = APPLICATION.YML

jpa = API
자바
퍼시스턴스 - 영속성
마이sql 언어를 써서 ~ 만들어줘
jpa:
database-platform: org.hibernate.dialect.MySQL8Dialect
properties:
hibernate:
format_sql: 'true'
hibernate:
ddl-auto: create
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: 'true'
설정방법
dialect - 방언.사투리
어떤 언어로 sql 만들껀지 - mysql8버전
jdbc 생산성이 떨어짐
mybatis 도입 유지보수 편하게 하려고 분리
API가 sql 자동으로 만들어줘
show-sql :'true' 하면 보입니다.


createdAt 카멜케이스
DB는 스네이크케이스
스네이크로 바뀝니다.
physical-strategy:
DTO에 적은 변수 그대로 이름을 가집니다.
package com.example.demo.entity;
import jakarta.persistence.Entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity // JPA API -> create table book
// JPA API(엔진 : Hibernate)|
// Object -> Table Mapping : ORM -> SQL 생성
public class Book {
private Long id;
private String title;
private int price;
private String author;
private int page;
}
@Entity 는
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
있어야합니다.
하이버네이트 엔진이 SQL을 만들어줍니다.
기본적인 CRUD
Mysql
@GeneratedValue(strategy = GenerationType.IDENTITY)
오라클은... 까먹었죠
package com.example.demo.entity;
import jakarta.persistence.*;
import lombok.*;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity // JPA API -> create table book
// JPA API(엔진 : Hibernate)|
// Object -> Table Mapping : ORM -> SQL 생성
public class Book {
@Id // PK
@GeneratedValue(strategy = GenerationType.IDENTITY) // 자동증가
private Long id;
@Column(name = "title", unique = true, nullable = false, length = 40) // length 기본255 varchar
private String title;
private int price;
private String author;
private int page;
}


자동완성이 되었습니다.
관계설정이 어렵습니다.
엔티티인 Book 클래스에서 관계를 지어야합니다.
MVCSR
M- - 모델
V - 뷰
C- 컨트롤
S- 서비스
R - DB

테이블이 되는데 dto로도 쓰잖아요
Entity가 되버리면 마음대로 추가하기가 어렵죠
ex) private int cnt; // 생성
Entity에다가 Book은 Table이고 BookDTO를 만듭니다.
Book클래스에는 마음대로 넣고 뺴고가 안됩니다.
//Book, BookDTO 두개를 만듭니다.
//Book(Entity+DTO)기능쓸 순있지만

public List<Book> findAll();
상속받으면 만들필요가 없습니다.
인터페이스 (바로 못쓰니가) 구현체가 세션 팩토리 하이버네이트도 구현체가 있습니다.
public class EntityManager implements BookRepository{
}
하이버네이트가 구현


오브젝트 기준으로 Book 만들어집니다.
클래스를 book 안됩니다. Book으로 합니다.
Table 로 갈때는 대소문자 상관없지만
객체중심으로 쿼리를 만들어져야합니다.
@Id
PK타입 Long형



반복문을 씁니다. 타임리프 사용

인헨서드 for문

findBy 뒤에 Title 이런 규칙을 하면 쿼리를 짜준다.
// 쿼리메서드(규칙을 가지고 메서드를 만들면 자동으로 SQL을 생성)
public Optional<Book> findByTitleAndPage(String title, int page);
// select * from Book b where b.title=title and b.page=page



delete
package com.example.demo.controller;
import com.example.demo.entity.Book;
import com.example.demo.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@Controller
public class HomeController {
private final BookService bookService;
public HomeController(BookService bookService) {
this.bookService = bookService;
}
// http://Localhost:8081/home
@GetMapping("/home")
public String home() {
return "home"; // home.html
}
@GetMapping("/list")
public String findAlL(Model model) {
List<Book> books = bookService.findAll();
model.addAttribute("books", books);
return "list";
}
@GetMapping("/delete/{id}")
public String deleteById(@PathVariable Long id){
bookService.deleteById(id);
return "redirect:/list";
}
}
package com.example.demo.service;
import com.example.demo.entity.Book;
import com.example.demo.repository.BookRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class BookService {
private final BookRepository bookRepository;
public List<Book> findAll(){
return bookRepository.findAll(); // select * from Book : JPQL->SQL전송
}
public void deleteById(Long id){
bookRepository.deleteById(id); // delete from Book b where b.id=?
}
}
셀렉트 다음 딜리트가 되네요



1번책이 있는지 없는지 모르니까 Optional에 넣고
없으면 null 처리합니다.