Spring Data Jpa 기본 세팅

반영환·2023년 5월 26일
0

스프링 이모저모

목록 보기
2/12
post-thumbnail

Spring Data Jpa 기본 세팅

start.spring.io 에서 프로젝트 생성

build.gradle

build.gradle에 의존성을 아래와 같이 추가한다

dependencies {
	// JPA
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    // lombok
	compileOnly 'org.projectlombok:lombok'
    // devTools
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
    //MySql
	runtimeOnly 'com.mysql:mysql-connector-j'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

https://nayha.tistory.com/740

  • mysql 연결 방법 변경

MySQL 세팅

DB 만들고, 계정 만들어서 권한 넘겨주기

CREATE DATABASE DB_NAME DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER '새계정'@'localhost' IDENTIFIED BY '비밀번호';
GRANT ALL PRIVILEGES ON DB_NAME.* TO '새계정'@'localhost';
FLUSH PRIVILEGES;

application.yml

src/main/resources/application.properties

spring:
  jpa:
    hibernate:
      ddl-auto: update
  datasource:
    url: jdbc:mysql://${MYSQL_HOST:localhost}:3306/DB_NAME
    username: USER_NAME
    password: PASSWORD
    driver-class-name: com.mysql.cj.jdbc.Driver

ddl-auto : DB Structure의 변동 가능성을 설정하는 옵션이다.

  • none : MySQL의 기본값. DB Structure의 변동을 허용 x , 오직 SELECT , UPDATE , INSERT, DELETE 만 가능
  • update : 주어진 ENTITY STRUCTURE에 따라서 Hibernate가 DB Structure를 변경
  • create : 매 번 DB를 새로 만들지만 close에 drop 하지 않음
  • create-drop : 매 번 DB를 새로 만들고 SessionFactory가 close 될 때 drop 함

You must begin with either create or update, because you do not yet have the database structure. After the first run, you can switch it to update or none, according to program requirements. Use update when you want to make some change to the database structure.

Model 생성

src/main/java/com/example/accessingdatamysql/User.java

@Entity : This tells Hibernate to make a table out of this class

@Entity need @NoArgsConstructor

@Id : The Customer object’s id property is annotated with @Id so that JPA recognizes it as the object’s ID

@GeneratedValue : indicate that the ID should be generated automatically

@GenerationType.IDENTITY를 사용하면 하이버네이트 테이블이 생성되지 않고 동일한 기능을 이용할 수 있다. IDENTITY만 사용하자

@Entity
@NoArgsConstructor(access=AccessLevel.PROTECTED)
@Builder
@AllArgsConstructor(access= AccessLevel.PROTECTED)
@Getter
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String email;

    private String password;

    private String role;
}

Repository 생성

src/main/java/com/example/accessingdatamysql/UserRepository.java

public interface UserRepository extends JpaRepository<User, Long> {

}

Controller 생성

src/main/java/com/example/accessingdatamysql/MainController.java

@Controller // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {

  private UserRepository userRepository;
  
  @Autowired
  public MainController(UserRepository userRepository) {
    this.userRepository = userRepository
  }
  
  @PostMapping(path="/add") // Map ONLY POST Requests
  @ResponseBody
  public String addNewUser (@RequestParam String name
      , @RequestParam String email) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request

    User n = new User();
    n.setName(name);
    n.setEmail(email);
    userRepository.save(n);
    return "Saved";
  }

  @GetMapping(path="/all")
  public @ResponseBody Iterable<User> getAllUsers() {
    // This returns a JSON or XML with the users
    return userRepository.findAll();
  }
}

출처 : https://spring.io/guides/gs/accessing-data-mysql/

profile
최고의 오늘을 꿈꾸는 개발자

0개의 댓글