实现用于为用户创建帖子的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选项卡下,插入帖子的描述。

restful-web-services-create-a-post.png

它会返回状态:201 Created。我们还可以通过执行查询select *from post;来在数据库中查看此帖子。
restful-web-services-create-a-post.png

标签: spring, Spring教程, Spring语言学习, Spring框架, Spring框架教程, Spring框架高级教程, spring boot, spring boot入门教程, spring boot学习教程, spring boot下载, spring boot框架入门, spring boot面试题, spring boot笔试题, spring boot学习指南, spring boot技术