面试题答案
一键面试- 首先定义
User
实体类:
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
@Entity
data class User(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
val name: String,
val age: Int
)
- 然后创建
UserRepository
接口:
import org.springframework.data.jpa.repository.JpaRepository
interface UserRepository : JpaRepository<User, Long> {
fun findAllByAgeGreaterThan(age: Int): List<User>
}
- 在服务层实现相关功能:
import org.springframework.stereotype.Service
import javax.persistence.EntityNotFoundException
@Service
class UserService(private val userRepository: UserRepository) {
fun saveUser(user: User): User {
return userRepository.save(user)
}
fun findUserById(id: Long): User {
return userRepository.findById(id).orElseThrow { EntityNotFoundException("User not found with id $id") }
}
fun findUsersByAgeGreaterThan(age: Int): List<User> {
return userRepository.findAllByAgeGreaterThan(age)
}
}
这样就完成了保存新用户、根据id
查询用户以及查询所有年龄大于20岁用户的功能。可以在控制器中注入UserService
来调用这些方法。例如:
import org.springframework.web.bind.annotation.*
import java.net.URI
@RestController
@RequestMapping("/users")
class UserController(private val userService: UserService) {
@PostMapping
fun saveUser(@RequestBody user: User): ResponseEntity<User> {
val savedUser = userService.saveUser(user)
return ResponseEntity.created(URI("/users/${savedUser.id}")).body(savedUser)
}
@GetMapping("/{id}")
fun findUserById(@PathVariable id: Long): ResponseEntity<User> {
val user = userService.findUserById(id)
return ResponseEntity.ok(user)
}
@GetMapping
fun findUsersByAgeGreaterThan(@RequestParam age: Int): ResponseEntity<List<User>> {
val users = userService.findUsersByAgeGreaterThan(age)
return ResponseEntity.ok(users)
}
}
上述代码在控制器中实现了对应的HTTP接口来调用服务层方法,注意这里使用了Spring的ResponseEntity
来处理响应,同时为了简化,省略了一些异常处理等细节,实际项目中可以根据需要完善。并且引入了必要的Spring Web依赖以支持HTTP请求处理。