JPA(Java Persistent API)
자바의 클래스와 DB의 테이블을 매핑하는 기술
객체지향적으로 데이터를 관리 -> 비즈니스 로직에 집중, 객체지향 개발 가능
신기했던 작명==SQL 기능
1) find / select
Article findByArticleid(int articleId);
select * from article where articleid = articleId;
이 기능을 한다
여기서 또 얘가 이상한게 FindByArticleId 로 id의 i를 대문자 I로 쓰면 article_id로 인식함;
2) order by
Article findFirstByEmailOrderByArticleidDesc(String email);
findFirst -> limit 1과 같음
OrderByArticleidDesc -> 말그대로 order by articleid desc
select * from article where email = email order by articleid desc limit 1;
3) save / insert, update
Article save(Article article);
save는 insert, update 2가지 기능을 한다..
update는 primary key 가 같으면 해주는 듯 싶다.
4) count
int countByNickname(String nickname);
5) delete
int deleteByArticleid(int articleid);
이러면 지워지는데 가끔 안 될때가 있다
@Transactional
int deleteByNotificationid(int notificationid);
@Transactional 을 붙힌다.. exception이 일어났을 때 자동으로 rollback을 시켜준다
@Transactional 관련 잘 정리된 글
[Java]@Transactional Annotation 알고 쓰자
초반 @Transactional 어노테이션에 대해 자세히 알아보지 않고,막연히 롤백때 사용한다고 하여 SQL C,U,D 를 할 때마다 메소드 위에 붙여서 사용하곤 하였다.하지만, 내 코드를 보신 선임께서 단지 @Tran
velog.io
6) paging 페이징
Page<Article> findAll(Pageable pageable);
Page<Article> findByIspublic(Pageable pageable, int ispublic);
컨트롤러에서는
Page<Article> articles =
articleDao.findByIspublic(PageRequest.of(page, 10, Sort.Direction.DESC,"articleid"),1);
인자
10 -> 10개 불러오겠다
Sort.Direction.DESC,"articleid") -> 최신순으로 정렬하기 위해서~
마지막 1은 select * from article where ispublic = 1; 의 1
7) jpa 에서 sql query 문 사용하기
@Query(value = "select * from article where date(createdat) = ?1 and email = ?2 order by articleid desc",
nativeQuery = true)
List<Article> articleAt(String date,String email);
@Query 를 쓰면 그냥 쿼리문을 사용할 수 있다.
nativeQuery = true가 뭔지는 모르지만 일단 무조건 붙히는 중 ㅎㅁㅎ
그리고 인자는 ?1 ?2 이런 식으로 순서를 맞춰주면 된다.
*프로젝트 알림 DAO 코드 중 일부*
package com.web.twl.dao.pinlikesfollow;
import java.util.List;
import javax.transaction.Transactional;
import com.web.curation.model.pinlikesfollow.Notification;
import com.web.curation.model.pinlikesfollow.NotificationMultiId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface NotificationDao extends JpaRepository<Notification, NotificationMultiId> {
Notification save(NotificationMultiId notification);
@Query(value =
"select * from notification where email = ?1 and date(createtime) > date(subdate(now(), INTERVAL 2 DAY)) order by notificationid desc"
, nativeQuery = true)
List<Notification> findAllIn30Days(String email);
@Transactional
int deleteByNotificationid(int notificationid);
Notification findNotificationByNotificationid(int notificationid);
}
Notification은 다중 Primary Key 여서 NotificationMultiId 를 선언했다..
그리고 기본키를 자바에서 임의로 setter 이용해서 업데이트(save)하면 에러남
8) Specification
아직 뭔진 잘 모르는데 이 코드를 좀 수정해야해서 아주 조금 구글링을 해봄
하지만 내가 원하는 toPredicate에 여러 조건을 동시에 주는 코드는 못 찾아서
그냥 내가 . 점 찍고 나오는 함수들 살펴보면서 실행해봤다
public class Search {
public static Specification<Article> searchByTitleOrderByArticleidDesc(final String title) {
return new Specification<Article>() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
query.orderBy(cb.desc(root.get("articleid")));
return cb.and(cb.equal(root.get("ispublic"), 1), cb.like(root.get("title"), "%" + title + "%"));
}
};
}
}
return cb.and(aaa, bbb); 이렇게 하면 조건 2개를 동시에 줄 수 있음
3개는 안 해봤는데 중첩하면 되지 않을까?....
'Web' 카테고리의 다른 글
[Backend] AWS ec2 서버 시간 설정 (0) | 2023.10.12 |
---|---|
[Backend] node.js + next.js API Routes 기초 (0) | 2023.10.11 |
[Frontend] JWT (0) | 2023.10.04 |
[Frontend] Node.js, Babel, Webpack (1) | 2023.05.19 |
[React] setState, props (0) | 2021.08.31 |