[Feature][Refactor] 7/27 - QueryDSL์ ์ฌ์ฉํ์ฌ ๊ฒ์ ๊ธฐ๋ฅ ๋ง๋ค๊ธฐ
dependency {
// querydsl
implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta'
annotationProcessor "com.querydsl:querydsl-apt:${dependencyManagement.importedProperties['querydsl.version'] }:jakarta"
annotationProcessor "jakarta.annotation:jakarta.annotation-api"
annotationProcessor "jakarta.persistence:jakarta.persistence-api"
}
@Configuration
public class QuerydslConfig {
@PersistenceContext
private EntityManager entityManager;
@Bean
public JPAQueryFactory jpaQueryFactory() {
return new JPAQueryFactory(entityManager);
}
}
~~CustomRepsitory
์ธํฐํ์ด์ค ๋ฐ ~~RepositoryImpl
ํด๋์ค ์์ฑ
RepositoryImpl
ํด๋์ค๋CustomRepository
์ธํฐํ์ด์ค๋ฅผ ์์ ๋ฐ๋๋ค.
public interface PostCustomRepository {
List<Post> findAllByOrderByCreatedAtDesc();
List<Post> findAllByUsername(String username);
Optional<Post> findByIdAndUsername(Integer id, String username);
}
import static com.crud.blog.entity.QPost.post;
@Repository
@RequiredArgsConstructor
public class PostRepositoryImpl implements PostCustomRepository {
private final JPAQueryFactory jpaQueryFactory;
@Override
public Optional<Post> findById(Integer id) {
Optional<Post> result = jpaQueryFactory
.selectFrom(post)
.where(post.id.eq(id))
.stream().findAny();
return result;
}
@Override
public List<Post> findAllByOrderByCreatedAtDesc() {
List<Post> result = jpaQueryFactory
.selectFrom(post)
.orderBy(post.createdAt.desc())
.fetch();
return result;
}
@Override
public List<Post> findAllByUsername(String username) {
List<Post> result = jpaQueryFactory
.selectFrom(post)
.where(post.username.eq(username))
.fetch();
return result;
}
@Override
public Optional<Post> findByIdAndUsername(Integer id, String username) {
Optional<Post> result = jpaQueryFactory
.selectFrom(post)
.where(post.id.eq(id).and(post.username.eq(username)))
.stream().findAny();
return result;
}
}
import static {Qํด๋์ค ๊ฒฝ๋ก}
ํํ๋ก importํ๊ฒ ๋๋ฉด, ๋ณ๋์ entity๋ฅผ ์์ฑํ ํ์์์ด ํด๋น property์ ์ ๊ทผํ ์ ์๊ฒ ๋๋ค.