SPRING 기본

2024. 12. 13. 17:17·웹공부/SPRING

1. SPRING 3요소

Spring은 자바 엔터프라이즈 기술을 사용함

  • Spring Framework : 클래스의 인스턴스를 생성하여 의존성 주입
  • Spring Container : 스프링에서 자바 객체들을 관리하는 공간
  • Bean : Spring에 생성되고 관리되는 자바 객체

기본적으로 객체 인스턴스를 싱글톤(클래스의 인스턴스 딱 1개만 생성됨)으로 관리

 

  • Controller : 사용자의 요청을 받아 결과를 뷰나 response로 전달
  • Service : 요구 사항을 처리하는 비지니스, 서비스 로직을 작성
  • Repository : DB를 통신

@Auowired : 의존성 주입이 쉽고 참조 관계를 눈으로 확인하기 어렵다.

 

src/main/java

java만 넣는 곳

@SpringBootApplication이 있는 곳으로 실행

package com.first.mvc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MvcApplication {

	public static void main(String[] args) {
		SpringApplication.run(MvcApplication.class, args);
	}

}

 

src/main/resources

templates : 디렉토리에는 템플릿파일을 저장

static : 이미지, CSS , JavaScript파일 등을 저장

application.properties :  프로젝트의 환경 변수, 데이터베이스 설정

 

src/test/java

작성한 모듈을 테스트하는 공간

 

build.gradle 

Gradle이 사용하는 환경 설정 파일로 필요한 소스파일을 컴파일 및 라이브러리 다운로드

 

2. MVC 디자인 패턴

 

1. Controller :  사용자의 요청을 처리하여 모델과 뷰 사이에서 데이터를 주고 받음

  • 뷰와 컨트롤러 사이에서 DispatcherServlet가 사용자 요청을 분석하고 요청을 처리할 컨트롤러를 찾아 호출함.
  • URL + PATH를 통해 사용자의 요청을 받음 👉🏻 @GetMapping("PATH")

package com.first.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("hello")
    public String helloUser(Model model){
        model.addAttribute("userName","rabat!");
        return "helloUser";
    }
}

 

 

2. Model : DB와 연동해 데이터를 처리함

JPA(Java Persistence API) : ORM(객체DB연결) 중에 하나로, 객체와 데이터베이스를 매핑함

  • ORM(객체 간 관계를 통해 SQL을 자동으로 연결)
  • @Entity : RDB 테이블과 매핑되는 클래스
public class jpaTest {
    @Test
    void test(){
        
        //EntityManagerFactory 생성
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("news");
        //EntityManager 생성
        EntityManager entityManager = emf.createEntityManager();
        //EntityTransaction 생성
        EntityTransaction tx = entityManager.getTransaction();
        //트랜잭션시작
        tx.begin();
        
        try{
            News news = new News("title","content"); // 엔티티 생성
            entityManager.persist(news); // 엔티티 영속화
            tx.commit(); // 커밋 => Insert 쿼리문 전송
        }catch (Exception e){
            tx.rollback();
        }finally {
            entityManager.close();
         }
    }
}

 

- 지연로딩 : 엔티티를 먼저 조회하고 우선 프록시 객체를 반환해서 필요할때 쿼리를 날려 가져오는 기능

 Member member = em.find(Member.class, "member1");
 Team team = member.getTeam();  // 프록시 객체
team.getName();  // 실제 사용 시점에초기화(데이터베이스조회)

 

3. View : 정보를 받아서 html을 만들어 줌(템플릿 엔진, mustache)

* 템플릿 엔진 : 동적 콘텐츠를 생성하는 데 사용되는 도구

  • {{userName}}처럼 데이터를 뚫어놓고 Controller가 넣어줌

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>내 이름은?</title>
</head>
<body>
    <h1>Hello {{userName}}</h1>
</body>
</html>

 

 

 

3. JPA와 영속성

영속성 컨텍스트 : 엔티티의 영구 저장소

EntityManagerFactory 생성

  • 영속 : em.persist(entity)로 객체가 영속성 컨텍스트에 들어간 상태
  • 준영속 : 영속에서 분리된 상태
  • 비영속 : 자바 메모리에만 있는 상태

 

Spring Data JPA

  • 엔티티메니저도 만들어줌
  • JpaRepository<객체, pk자료형>에 CRUD기능이 모두 들어있음. 
@Repository
public interface NewsRepository extends JpaRepository<News, Long> {
}

 

 

- 실습해보기

 

- application.yml

server : h2-console 접속

datasource : 데이터베이스의 기본정보

h2: 콘솔 사용 유무 및 위치

jpa: 데이터 시트를 DDL로 관리, SQL확인

server:
  servlet:
    encoding:
      force-response: true
spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:~/demodb
    username: sa
    password: 1234
  h2:
    console:
      enabled: true
      path: /h2-console
  jpa:
    hibernate:
      ddl-auto: update
      show-sql: true

 

- News라는 Entity생성

@Entity에 @Id는 꼭 필요

@GeneratedValue : 없으면 자동증가되는 키

@Column : 필요한 컬럼 추가(안쓰면 기본적으로 해줌)

@Getter, @Setter : 자동으로 get, set 추가해줌

@NoArgsConstructor : 기본생성자

@AllArgsConstructor : 전체생성자

아래 생성자를 생성하지 않아도 됨

    public News() {
    }

    public News(Long newsId, String title, String content) {
        this.newsId = newsId;
        this.title = title;
        this.content = content;
    }

 

 

- News

package com.example.jpa.domain;

import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;


@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class News {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long newsId;

    @Column(name = "news_title", nullable = false, length = 255)
    private String title;

    @Column(nullable = false)
    private String content;

    @ManyToOne
    @JoinColumn(name = "user_id")
    @JsonBackReference // 무한 루프 없애기
    private User user;
}

 

- User

package com.example.jpa.domain;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor

public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username")
    private String name;

    @Enumerated(EnumType.STRING)
    private RoleType role;

    @Temporal(TemporalType.DATE)
    private Date birthday;

    @CreationTimestamp
    private LocalDateTime createAt;

    @UpdateTimestamp
    private LocalDateTime updateAt;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    @JsonManagedReference //무한루프 없애기
    private List<News> news;
}

enum RoleType {
    ADMIN, USER
}

 

http://localhost:8080/h2-console

 

일대다

- 필드 이름

 public class News {
 ...
 
     @ManyToOne
     @JoinColumn(name = "user_id")
     private User user;
)

 

- 검색 조회

public class User {
 ...
 	@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
 	private List<News> news;
 }

 

'웹공부 > SPRING' 카테고리의 다른 글

페이지네이션  (0) 2024.12.17
BootStrap 실습 (Create, Read)  (0) 2024.12.16
Intellj Community Edition에서 SPRING 작동하는 법  (0) 2024.12.13
스파르타 코딩 클럽 - Spring 4주차  (0) 2024.07.26
스파르타 코딩 클럽 - Spring 3주차  (0) 2024.07.25
'웹공부/SPRING' 카테고리의 다른 글
  • 페이지네이션
  • BootStrap 실습 (Create, Read)
  • Intellj Community Edition에서 SPRING 작동하는 법
  • 스파르타 코딩 클럽 - Spring 4주차
Rabet
Rabet
  • 블로그 메뉴

    • 관리자
    • 글쓰기
  • Rabet
    卯
    Rabet
  • 전체
    오늘
    어제
    • Root (139)
      • KT AIVLE School (85)
        • Start (4)
        • Python프로그래밍 & 라이브러리 (6)
        • 데이터 처리 및 분석 (7)
        • 데이터 분석 및 의미 찾기 (7)
        • 웹크롤링 (10)
        • 머신러닝 (10)
        • 딥러닝 (6)
        • 시각지능 딥러닝 (10)
        • 언어지능 딥러닝 (6)
        • JAVA (4)
        • SQL (2)
        • 가상화 클라우드 (5)
        • 프로젝트 (8)
      • QA (2)
        • 오류사항 (1)
      • 웹공부 (14)
        • SPRING (11)
        • React (1)
      • 코딩 알고리즘 스터디 (23)
      • 코딩테스트 (9)
        • JAVA (8)
        • HTML (1)
      • CS공부 (3)
      • 자격증공부 (3)
        • 정보처리기사 (1)
        • 컴퓨터활용능력 1급 (1)
        • AICE Associate (1)
        • CSTS (0)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
Rabet
SPRING 기본
상단으로

티스토리툴바