简体   繁体   中英

Spring controller with MongoDB POST and GET records

I need help understanding how and why I should use controllers when I want to post something in my DB and retrieving it. When I only use Post.java and PostRepository.java, it seems to work when I insert data as well as retrieving the entire database in my "/posts" path. Inside the file I have a posts array containing all the entries.

Post.java

public class Post {

@Id private long id;

private String content;
private String time;
private String gender;  
private String age;


// Constructors

public Post() {

}

public Post(long id, String content, String time, String gender, String age) {
    this.id = id;
    this.content = content;
    this.time = time;
    this.gender = gender;
    this.age = age;
}

// Getters

public String getContent() {
    return content;
}

public long getId() {
    return id;
}

public String getTime() {
    return time;
}

public String getGender() {
    return gender;
}

public String getAge() {
    return age;
}

PostRepository.java

@RepositoryRestResource(collectionResourceRel = "posts", path = "posts")
public interface PostRepository extends MongoRepository<Post, String> {

List<Post> findPostByContent(@Param("content") String content);
}

PostController.java

@RestController
public class PostController {    

private final AtomicLong counter = new AtomicLong();

//Insert post in flow 
@RequestMapping(value="/posts", method = RequestMethod.POST)
public Post postInsert(@RequestBody Post post) {
    return new Post(counter.incrementAndGet(), post.getContent(), post.getTime(), post.getGender(), post.getAge());
}

//Get post in flow
@RequestMapping(value="/posts", method = RequestMethod.GET)
public Post getPosts() {
    return null;  //here I want to return all posts made using postInsert above.
}
}

When I use my controllers I can post data but it is not saved in a json file so when I restart my application I start from id: 1 again. However, without the controller the data is saved. Why is this happening? How can I arrange so that with controllers the data is saved as well? I know this might be a stupid question but I don't know what to do.

The controllers are here to manage the requests made through your apps. Whether you use @RestController or @Controller give a completely different result.

Therefore, the REST approach is to see your objects as resources. Here JSON is the default format to represent the resources you want to expose.

Using your PostRepository you have to save properly data in the store before exposing them with the return statement, ( eg the return just display the resource ( your post ) in JSON format . To save a post you have to use save() method for MongoRepository

    //Insert post in flow 
@RequestMapping(value="/posts", method = RequestMethod.POST)
public Post postInsert(@RequestBody Post post) {

// you have to use your repository to be able to CRUD operations in the store

final PostRepository postRepository;    

// save the post in the store

postRepository.save(new Post(counter.incrementAndGet(), post.getContent(), post.getTime(), post.getGender(), post.getAge()));

HttpHeaders httpHeaders = new HttpHeaders();
                    httpHeaders.setLocation(ServletUriComponentsBuilder
            .fromCurrentRequest().build().toUri());

return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

To get all the posts in the store you use the repository as for save data.

    //Get post in flow
@RequestMapping(value="/posts", method = RequestMethod.GET)
public Post getPosts() {
    return this.postRepository.findAll();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM