인프런 커뮤니티 질문&답변

준준님의 프로필 이미지
준준

작성한 질문수

자바 ORM 표준 JPA 프로그래밍 - 기본편

소개

JPQL 로 작성한 문법 테스트 코드로 작성해 볼 수 있을까요?

작성

·

463

0

안녕하세요.
JPQL 로 쿼리를 작성하고 실제 데이터가 들어가는지 보려고 합니다.
 
우선, main 함수에서 직접 넣는거는 되는 것을 확인했습니다.
 
그리고 제가 해보고 싶었던거는 테스트 코드로 작성해보는 것이였습니다.
 
그런데 Bean을 못찾는다는 에러가 발생했습니다.
 
구글링도 해보고 빈 등록을 다양하게 해보면서 접근법을 다르게도 해봤는데 해결이 안되네요 ㅠㅠ
 
혹시 제 코드를 보시고 어디에 문제가 있는지 알 수 있을까요?
 
제가 작성한 코드입니다.
 
[ JPQLRepository ]
@Transactional
@Repository
public class JPQLMemberRepository implements MemberRepository{

    @PersistenceContext
    private final EntityManager em;

    @Autowired
    public JPQLMemberRepository(EntityManager em) {
        this.em = em;
    }

    public EntityTransaction getTx() {
        return em.getTransaction();
    }

    public Member save(Member member) {
        em.persist(member);
        return member;
    }

    public void emClose() {
        em.close();
    }

    @Override
    public Optional<Member> findByid(Long id) {
        return Optional.empty();
    }

    @Override
    public Optional<Member> findByname(String name) {
        List<Member> result = em.createQuery(
                "SELECT m FROM Member m WHERE m.name = :name",
                Member.class
        ).setParameter("name", name).getResultList();

        System.out.println("--------------------------------");
        for (Member i : result) {
            System.out.println("member:" + i);
        }
        System.out.println("--------------------------------");

        return result.stream().findAny();
    }
}

[ SpringConfig ]
@Configuration
public class SpringConfig {

    @Bean
    public EntityManagerFactory getEnf() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("5xik");
        return emf;
    }

    @Bean
    public EntityManager getEm() {
        return getEnf().createEntityManager();
    }

    @Bean
    public MemberRepository memberRepository() {
        return new JPQLMemberRepository(getEm());
    }
}

[ TestCode ]
@SpringBootTest
@Transactional
class JPQLMemberRepositoryTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);

    MemberRepository repository = ac.getBean("memberRepository",JPQLMemberRepository.class);

    EntityTransaction tx = repository.getTx();

    @Test
    @Commit
    void insertData() {
        tx.begin();
        try{
            Member member = new Member();
            member.setName("sungjun");
            member.setPhonenumber("010");

            repository.save(member);
            Optional<Member> result =  repository.findByname(member.getName());

            Assertions.assertThat(result).isEqualTo(member);
            tx.commit();

        } catch (Exception e){
            tx.rollback();
        } finally {
            //repository.emClose();
        }
        //ac.close();
    }
}




그리고 아직 close를 하는 부분은 구현을 안해놔서
주석처리를 해놨습니다 !


감사합니다.








답변 1

0

안녕하세요. 준준님, 공식 서포터즈 OMG입니다.

본 강의는 스프링부트 환경도 아니고, 별도의 테스트를 작성하지는 않기 때문에 해당 내용은 숙지하고 계시다고 가정하고 구현하였습니다.

applicatio.properties

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:testdb

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

package com.example.demo.domain;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Getter @Setter
public class Member {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private String name;
}

 

package com.example.demo.repository;

import com.example.demo.domain.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.List;
import java.util.Optional;

@Transactional
@Repository
public class JPQLMemberRepository implements MemberRepository{

    @Autowired
    private EntityManager em;


    public EntityTransaction getTx() {
        return em.getTransaction();
    }

    public Member save(Member member) {
        em.persist(member);
        return member;
    }

    public void emClose() {
        em.close();
    }

    @Override
    public Optional<Member> findById(Long id) {
        return Optional.empty();
    }

    @Override
    public Optional<Member> findByName(String name) {
        List<Member> result = em.createQuery(
                "SELECT m FROM Member m WHERE m.name = :name", Member.class)
                .setParameter("name", name)
                .getResultList();

        return result.stream().findAny();
    }
}

 

package com.example.demo.repository;

import com.example.demo.domain.Member;

import java.util.Optional;

public interface MemberRepository {
    Optional<Member> findById(Long id);

    Optional<Member> findByName(String name);
    Member save(Member member);
}

 

package com.example.demo.repository;

import com.example.demo.domain.Member;
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 static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
@Transactional
class JPQLMemberRepositoryTest {

    @Autowired
    MemberRepository repository;

    @Test
    void insertData() {
        Member member = new Member();
        member.setName("sungjun");

        repository.save(member);
        Member result = repository.findByName(member.getName()).get();

        assertThat(result).isEqualTo(member);
    }
}


감사합니다.

준준님의 프로필 이미지
준준
질문자

오.. 감사합니다 !!!

준준님의 프로필 이미지
준준

작성한 질문수

질문하기