본문 바로가기
Spring

[Spring] spring 프로젝트 MySQL 연결하기

by clolee 2022. 8. 31.

build.gradle

dependencies 추가

 

application.properties 설정 추가

# MySQL 설정
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JDBC URL of the database.
# spring.datasource.url=jdbc:mysql://localhost:{port}/{DBname}?{options}
spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=test
spring.datasource.password=1234

spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true

 

main method 정상 실행 확인

 

Project Class, Interface

 

Memo class

package com.sto.salepurchase.backstosalepurchase;

import lombok.*;
import net.bytebuddy.build.ToStringPlugin;

import javax.persistence.*;

@ToString
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "tbl_memo")
@Entity
public class Memo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private  Long id;

    @Column(length = 200, nullable = false)
    private String memoText;
}

 

BackStoSalePurchaseApplication main method run

Memo class 실행

테이블 생성에 필요한 sql 기록

생성된 database table MySQL workbench 에서 확인

 

 

 

CRUD test

 

back-sto-sale-purchase/src/test/java/com/sto/salepurchase/backstosalepurchase/MemoRepository.java

package com.sto.salepurchase.backstosalepurchase;

import org.springframework.data.jpa.repository.JpaRepository;

public interface MemoRepository extends JpaRepository<Memo, Long> {
}

 

back-sto-sale-purchase/src/test/java/com/sto/salepurchase/backstosalepurchase/MemoRepositoryTest.java

@SpringBootTest
public class MemoRepositoryTest {

    @Autowired
    MemoRepository memoRepository;
    
}

Create

    // Create
    @Test
    public void InsertDummies() {
        IntStream.rangeClosed(1, 10).forEach(i -> {
            Memo memo = Memo.builder().memoText("Sample..." + i).build();
            memoRepository.save(memo);
        });
    }

 

 

Read

    // Read
    @Test
    public void SelectDummies() {

        Long id = 10L;
        Optional<Memo> result = memoRepository.findById(id);
        System.out.println("===========================");

        if (result.isPresent()) {
            Memo memo = result.get();
            System.out.println(memo);
        }
    }

 

 

Update

    // Update
    @Test
    public void UpdateDummies() {
        Memo memo = Memo.builder().id(10L).memoText("Update Text").build();

        memoRepository.save(memo);
    }

 

 

Delete

// Delete
@Test
public void deleteDummies() {
    Long id = 10L;

    memoRepository.deleteById(id);
}

 

 

 

 

참고 : 

https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties

https://dev-coco.tistory.com/85

https://i5i5.tistory.com/707

 

댓글