implementation 'org.springFramework.boot:spring-boot-starter-data-jpa'
spring.dataSource.url=jdbc:h2:tcp://localhost/~/test
spring.dataSource.driver-class-name=org.h2.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
/* Member */
@Entity
public class Member {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) // DB가 ID를 자동으로 생성해줌을 표시
private Long id;
@Column(name="username") // DB의 column명이 username인 것과 맵핑
private String name;
...
getter/setter
}
/* JpaMemberRepository */
public class JpaMemberRepository implements MemberRepository {
// JPA Manager는 EntityManager로 동작함
// spring boot가 EntityManager를 만들어줌
private final EntityManager em;
public JpaMemberRepository(EntityManager em){
this.em = em;
}
@Override
public Member save(Member member){
em.persist(member);
return member;
}
@Override
public Optional<Member> findById(Long id) {
Member member = em.find(Member.class, id);
return Optional.ofNullable(member);
}
@Override
public Optional<Member> findByName(String name) {
List<Member> result = em.createQuery("select m from Member m where m.name = "name", Member.class)
.setParameter("name", name)
.getResultList();
return result.stream().findAny();
}
@Override
public List<Member> findAll() {
// 객체를 대상으로 Query를 날림
// select의 대상이 *이 아닌 Member Entity 자체
return em.createQuery("select m from Member m", Member.class)
.getResultList();
}
}
@Transactional
public class MemberService{
...
}
@Configuration
public class SpringConfig {
private EntityManager em;
@Autowired
public SpringConfig(EntityManager em){
this.em = em;
}
...
@Bean
public MemberRepository memberRepository(){
return new JdbcMemberRepository();
}
}
/* SpringDataJpaMemberRepository */
public interface SpringDataJpaMemberRepository extends JpaRepository<Member, Long>, MemberRepository {
@Override
Optional<Member> findByName(String name);
}
/* SpringConfig */
private final MemberRepository memberRepository;
@Autowired // 생성자 하나, 생략 가능
public SpringConfig(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
// @Bean (생략 가능)
// public MemberRepository memberRepository(){
// return new MemoryMemberRepository();
// }
}
findByName()
, findByEmail()
처럼 메서드 이름만으로 조회 기능 제공참고
JPA와 스프링 데이터 JPA를 기본으로 사용하고, 복잡한 동적 쿼리는 Querydsl 라이브러리 사용