start.spring.io
에서 프로젝트 생성
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'
}
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;
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.
src/main/java/com/example/accessingdatamysql/User.java
@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;
}
src/main/java/com/example/accessingdatamysql/UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> {
}
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();
}
}