SpringBoot教程-实现用于为用户创建帖子的POST服务
实现用于为用户创建帖子的POST服务
步骤1: 打开UserJPAResource.java文件,创建一个PostMapping来创建帖子。
@PostMapping("/jpa/users/{id}/posts")
public ResponseEntity<Object> createUser(@PathVariable int id, @RequestBody Post post)
{
Optional<User> userOptional= userRepository.findById(id);
if(!userOptional.isPresent())
{
throw new UserNotFoundException("id: "+ id);
}
User user=userOptional.get();
//map the user to the post
post.setUser(user);
//save post to the database
postRepository.save(post);
//getting the path of the post and append id of the post to the URI
URI location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(post.getId()).toUri();
//returns the location of the created post
return ResponseEntity.created(location).build();
}
步骤2: 创建一个帖子的Repository。
package cn.javatiku.server.main.user;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PostRepository extends JpaRepository<Post, Integer>
{
}
步骤3: 打开Postman,使用URI http://localhost:8080/jpa/users/102/posts
发送一个POST请求。在Body选项卡下,插入帖子的描述。
它会返回状态:201 Created。我们还可以通过执行查询select *from post;来在数据库中查看此帖子。