@Repository
interface UserRepository: JpaRepository<User, Long> {
}
@RestController
@RequestMapping("/users")
class UserController(
private val userService: UserService
) {
@PostMapping
fun createUser(@RequestBody request: CreateUserRequest): ResponseEntity<UserResponse> {
val user = userService.createUser(request)
return ResponseEntity.ok(
UserResponse(
id = user.id,
name = user.name,
email = user.email
)
)
}
}
처음에는 기본 형태에 @Entity
만 붙였더니 테이블명을 "user"로 지어줬다.
@Entity
data class User(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
val name: String,
val password: String,
val email: String
)
그러나 여러 사용자가 포함된 테이블이라는 것을 강조하고자 테이블명을 "users"로 짓고 싶다.
@Entity
@Table(name = "users")
data class User(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
val name: String,
val password: String,
val email: String
)
그리고 나서 API를 호출해주면
$ curl -X POST -H "Content-Type: application/json" -d '{"name":"John", "password":"password123", "email":"john@example.com"}' http://localhost:8080/users
{"id":1,"name":"John","email":"john@example.com"}
DB에 row가 추가된 것을 확인할 수 있다.
mysql> SELECT * FROM users;
+----+------------------+------+-------------+
| id | email | name | password |
+----+------------------+------+-------------+
| 1 | john@example.com | John | password123 |
+----+------------------+------+-------------+
1 row in set (0.00 sec)
물론 password는 저런 plain text로 저장하면 안될텐데, 그건 나중에 알아보자.