2016년 11월 19일 토요일

Spring Boot - JPA



환경:

  1. IDE: STS
  2. DB: H2
  3. Test: Junit, Mockito
  4. Build: Gradle

JPA 프로젝트 생성


  • File > New > Spring Starter Project 선택
  • 그림과같이 Name 및 Package 넣고 Next


  • 그림과 같이 JPA 및 H2 선택 후 Next 하여 프로젝트 생성


Spring Boot 과 JPA를 이용하여 간단하게 CRUD 예제를 만듦.



Entity 클래스 작성

@Entity
public class Member {

 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private long id;
 
 @Column
 private String name;
 
 @Column
 private int age;

 public long getId() {
  return id;
 }

...
}

Repository 클래스 작성


CrudRepository를 상속한 인터페이스 만든다.

public interface Repository extends CrudRepository<Member Long> {
 
}


실행 클래스 JpaApplication 작성


run()메소드는 console로 입력값을 받아서 CRUD 처리. 자세한것은 소스 참조

@SpringBootApplication
public class JpaApplication implements CommandLineRunner {

 @Autowired Repository repository;
 
 public static void main(String[] args) {
  SpringApplication.run(JpaApplication.class, args);
 }
 
 public void run(String... args) throws Exception {
  int select = 0;
  
  while(select != 9){
   Scanner sc = new Scanner(System.in);
   System.out.print("select number insert(1), update(2), delete(3), exit(9)?");
   select = sc.nextInt();
   
   if(select == 1){
    insert();
   } else if(select == 2){
    update();
   } else if(select == 3){
    delete();
   }
   
   result();
  }
  
  if(select == 9){
   System.out.print("Exit!! \n");
   System.exit(0);
  }
 }
}


댓글 없음:

댓글 쓰기