[Spring JPA #12] 커스텀 리포지토리

 

package org.kyhslam.jpa.Post;

import javax.persistence.*;
import java.util.Date;

@Entity
public class Post {


    @Id @GeneratedValue
    private Long id;

    private String title;

    @Lob
    private String content;

    @Temporal(TemporalType.TIMESTAMP)
    private Date created;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }
}
package org.kyhslam.jpa.Post;
import java.util.List;

public interface PostCustomRepository {
    List<Post> findMyPost();
}
package org.kyhslam.jpa.Post;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

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

@Repository
@Transactional
public class PostCustomRepositoryImpl implements PostCustomRepository {

    @Autowired
    EntityManager entityManager;

    @Override
    public List<Post> findMyPost() {
        System.out.println("custom findMyPost");
        return entityManager.createQuery("SELECT p FROM Post AS p", Post.class).getResultList();

    }
}
package org.kyhslam.jpa.Post;

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

public interface PostRepository extends JpaRepository<Post, Long>, PostCustomRepository {
}

 

테스트

package org.kyhslam.jpa;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.kyhslam.jpa.Post.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DataJpaTest
public class PostRepositoryTest {

    @Autowired
    PostRepository postRepository;

    @Test
    public void crud(){
        postRepository.findMyPost();
    }
}

'📚 Spring > Spring JPA' 카테고리의 다른 글

[정리] 영속성 컨텍스트 및 엔티티  (0) 2022.03.15
@JsonIgnore  (0) 2020.09.04
[Spring JPA #11] 쿼리 실습  (0) 2020.07.19
[Spring JPA #7] Query  (0) 2020.07.15
[Spring JPA #6] Fetch  (0) 2020.07.15

댓글

Designed by JB FACTORY