스프링에서 JPA를 편리하게 사용할 수 있도록 지원하는 프로젝트이다.
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:~/order;DB_CLOSE_ON_EXIT=FALSE
username: sa
password:
jpa:
open-in-view: false
hibernate:
ddl-auto: create-drop
show-sql: true
properties:
hibernate.format_sql: true
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrderRepository extends JpaRepository<Order, String> {
}
@Test
void JPA_query() {
Order order = orderRepository.findById(uuid).get(); // SELECT * FROM orders WHERE id = ?
List<Order> all = orderRepository.findAll(); // SELECT * FROM orders
orderRepository.existsById(uuid);
}
// 실행결과
Hibernate: select order0_.id as id1_3_0_, order0_.member_id as member_i5_3_0_, order0_.memo as memo2_3_0_, order0_.order_datetime as order_da3_3_0_, order0_.order_status as order_st4_3_0_ from orders order0_ where order0_.id=?
Hibernate: select order0_.id as id1_3_, order0_.member_id as member_i5_3_, order0_.memo as memo2_3_, order0_.order_datetime as order_da3_3_, order0_.order_status as order_st4_3_ from orders order0_
Hibernate: select count(*) as col_0_0_ from orders order0_ where order0_.id=?
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
public interface OrderRepository extends JpaRepository<Order, String> {
List<Order> findAllByOrderStatus(OrderStatus orderStatus);
// SELECT * FROM orders WHERE order_status = 'OPEND'
List<Order> findAllByOrderStatusOrderByOrderDatetime(OrderStatus orderStatus);
// // SELECT * FROM orders WHERE order_status = 'OPEND' ORDER BY order_datetiem
}
@Test
void NAMED_QUERY() {
orderRepository.findAllByOrderStatus(OrderStatus.OPENED);
orderRepository.findAllByOrderStatusOrderByOrderDatetime(OrderStatus.OPENED);
}
// 실행 결과
Hibernate: select order0_.id as id1_3_, order0_.member_id as member_i5_3_, order0_.memo as memo2_3_, order0_.order_datetime as order_da3_3_, order0_.order_status as order_st4_3_ from orders order0_ where order0_.order_status=?
Hibernate: select order0_.id as id1_3_, order0_.member_id as member_i5_3_, order0_.memo as memo2_3_, order0_.order_datetime as order_da3_3_, order0_.order_status as order_st4_3_ from orders order0_ where order0_.order_status=? order by order0_.order_datetime asc
public interface OrderRepository extends JpaRepository<Order, String> {
...
@Query("SELECT o FROM Order AS o WHERE o.memo LIKE %?1%")
Optional<Order> findByMemo(String memo);
}
@Test
void NAMED_QUERY() {
Optional<Order> order = orderRepository.findByMemo("부재시");
Order entity = order.get();
log.info("{}", entity.getMemo());
}
// 실행 결과
Hibernate: select order0_.id as id1_3_, order0_.member_id as member_i5_3_, order0_.memo as memo2_3_, order0_.order_datetime as order_da3_3_, order0_.order_status as order_st4_3_ from orders order0_ where order0_.memo like ?
2021-09-11 15:46:04.524 INFO 19811 --- [ main] c.k.l.domain.order.OrderRepositoryTest : 부재시 전화주세요.
참고