[JPA] Entity와 Repository
- Java/SpringBoot
- 2022. 1. 12. 23:06

Entity 클래스와 Repository 인터페이스는 쌍으로 같은 위치에 존재해야한다.
이는 쿼리매퍼의 Dao패키지와 같은 레벨 정도라고 생각하면 좋은 것 같다.
Repository 인터페이스가 존재는 Entity에 접근하기 위함인듯~? 접근법이 있다!
Posts.java
package com.jhs.book.springboot.domain.posts; import com.jhs.book.springboot.domain.BaseTimeEntity; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Getter // 모든 필드의 Getter 메소드 자동 생성 (롬복) @NoArgsConstructor // 기본 생성자 자동 추가 (롬복) @Entity // 테이블과 링크될 클래스임을 나타냄 (기본값으로 클래스의 카멜케이스 -> 캐밥케이스로 테이블 이름 매핑(HelloWorl.java -> hello_world table)) publicclassPostsextendsBaseTimeEntity { @Id // PK 필드 @GeneratedValue(strategy = GenerationType.IDENTITY) // auto_increment privateLongid; @Column(length = 500, nullable = false) // default로 varchar(255) & nullable=true privateStringtitle; @Column(columnDefinition = "TEXT", nullable = false) privateStringcontent; privateStringauthor; @Builder // 빌더 패턴 클래스 생성, 생성자 상단에 선언 시 생성자에 포함된 필드만 빌더에 포함 (롬복) publicPosts(Stringtitle, Stringcontent, Stringauthor) { this.title = title; this.content = content; this.author = author; } publicvoidupdate(Stringtitle, Stringcontent) { this.title = title; this.content = content; } } |
- setter는 entity 클래스에서 절대 만들지 않는다. 대신 목적과 의도를 나타내는 메소드를 추가해야함!
PostsRepository.java
package com.jhs.book.springboot.domain.posts; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; publicinterfacePostsRepositoryextendsJpaRepository<Posts, Long>{ @Query("SELECT p FROM Posts p ORDER BY p.id DESC") List<Posts> findAllDesc(); } |
- JpaRepository<Entity 클래스, PK 타입> 상속
- Entity 접근자
- @Repository 추가할 필요없음. 단, Entity 클래스와 같은 경로에 위치해야함.
'Java > SpringBoot' 카테고리의 다른 글
파라미터 어노테이션 생성 (0) | 2022.03.16 |
---|---|
JPA에서 실제 실행 쿼리(SQL) 로그 설정 ON/OFF (0) | 2022.03.07 |
2021.12.31 Springboot2 build.gradle 백업본 (0) | 2021.12.31 |
[IntelliJ Springboot JUnit 에러] No tests found for given includes (0) | 2021.12.31 |
only buildscript {} and other plugins {} script blocks are allowed before plugins {} blocks, no other statements are allowed (0) | 2021.12.15 |
이 글을 공유하기