2018년 12월 10일 월요일

JPA 기본 골격.

// Entity
@Entity
@Data
@NoArgsConstructor
public class Member {
 @Id // javax.persistence.Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private long id;

 @Column(nullable = false, length = 30)
 private String name;

 private int age;

 public Member(String name, int age) {
  this.name = name;
  this.age = age;
 }

 @Override
 public String toString() {
  return String.format("Member[id=%d, name='%s', age=%d]", id, name, age);
 }
}

// Repository
public interface MemberRepository extends CrudRepository<Member, Long> {
 List<Member> findbyNameAndAgeLessThan(String name, int age);
 List<Member> findbyNameAndAgeLessThanOrderByAgeDesc(String name, int age);

 @Query("select t from Member t where name=:name and age < :age")
 List<Member> findByNameAndAgeLessThan(@Param("name") String name, @Param("age") int age);
}

// Booter
@EntityScan(basePackages="package.name")
@EnableJpaRepositories(basePackages="another.package.name")
@SpringBootApplication
public class TestJpaApplication {
 public static void main(String[] args) {
  SpringApplication.run(TestJpaApplication.class, args);
 }
}

참고로 JPA가 제공하는 Repository의 상속 계층은 다음과 같다.
CrudRepository만 써도 일반적인 CRUD 작업은 할 수 있다.

1. public interface Repository<T, ID extends Serializable>
2. public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID>
3. public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID>
4. public interface JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID>

https://www.concretepage.com/spring-boot/spring-boot-crudrepository-example

댓글 없음:

댓글 쓰기