jpa _mariadb 연결

su dong·2023년 5월 19일
1

1. Bulid.gradle파일에 jpa 관련 추가

implementation 'org.springframework.boot:spring-boot-starter-jdbc'
	runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

2. Application properties에 정보 추가

spring.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/project
spring.datasource.username=root
spring.datasource.password=tkddlsqkr@1
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true 

3. class 에 @Entity 붙이기

  1. 만약 테이블과 class이름이 다르다면 @Table(name = “테이블 이름”)해주면 된다.
@Entity(name = "memo")
public class Memo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String text;
}

4. jpaMemoRepository 작성

너무 간단한 거 아닌가...

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import zerobase.weather.domain.Memo;

//jparepository안에 이미 save, findInt, findAll같은 것들이 다 선언되어 있다.
@Repository
public interface JpaMemoRepository extends JpaRepository<Memo, Integer> {

}

5. jpaMemoRepositoryTest

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import zerobase.weather.domain.Memo;
import zerobase.weather.repository.JpaMemoRepository;

import java.util.List;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

@SpringBootTest
@Transactional
public class JpaMemoRepositoryTest {
    @Autowired
    JpaMemoRepository jpaMemoRepository;


    @Test
    void findByIdTest(){
        //given
        Memo newMemo2 = new Memo(30, "this is memo2");
        //when
        Memo memo = jpaMemoRepository.save(newMemo2);

        //then
        Optional<Memo> result = jpaMemoRepository.findById(memo.getId());
        assertEquals(result.get().getText(), newMemo2.getText());
    }

    @Test
    void insertTest() {
        //given
        Memo jpa = new Memo(10, "jpa");
        //when
        jpaMemoRepository.save(jpa);
        //then
        List<Memo> all = jpaMemoRepository.findAll();
        assertTrue(all.size() > 0);
    }
}
profile
사람들을 돕는 문제 해결사, 개발자 sudong입니다. 반갑습니다. tkddlsqkr21@gmail.com

0개의 댓글