简体   繁体   中英

findAll() is not working in SpringBoot Rest MySql CRUD operations application

I am trying to perform CRUD operations using spring boot+REST+MySQL along crudrepository interface,when i try to get data from database,i am getting empty list back.I found that findAll() method in my application is not working as expected.

My Application class

@SpringBootApplication
public class Blog {

public static void main(String[] args) {
        SpringApplication.run(Blog.class, args);
        System.out.println("Application Started");
    }}

My Entity class

@Entity
@Table(name="posts")
public class Post {
    @Id
    @Column(name="id")
    int postId;
    @Column(name="title")
    String title;
    @Column(name="body")
    String body;

    public Post() {}
    public Post(int postId, String title, String body) {

        this.postId = postId;
        this.title = title;
        this.body = body;
    } //getters and setters and toString()

Controller Class

@RestController
public class PostsController {
    @Autowired
    private PostsService service;

    @RequestMapping("/posts")
    public List<Post> getPosts(){
        return service.getPosts();
    }
    @RequestMapping("/posts/{id}")
    public Post getPost(@PathVariable int id) {
        return service.getPost(id);
    }

    @RequestMapping(method=RequestMethod.POST, value="/posts")
    public void addPost(@RequestBody Post listElement) {
         service.addPost(listElement);
    }

    @RequestMapping(method=RequestMethod.PUT, value="/posts/{id}")
    public void updatePost(@RequestBody Post post) {
         service.updatePost(post);
    }

    @RequestMapping(method=RequestMethod.DELETE, value="/posts/{id}")
    public void deletePost(@PathVariable int id) {
         service.deletePost(id);
    }

Service Classs

@Service
public class PostsService {
    @Autowired
    private PostRepository repo;

    public List<Post> getPosts(){
        List<Post> list = new ArrayList<>();
        System.out.println("at Service");
        for(Post post: repo.findAll()) {
            System.out.println("in for loop");
            list.add(post); 
        }
        return list;
    }

    public Post getPost(int id) {
        return repo.findById(id).get();
    }

    public void addPost(Post listElement) {
        repo.save(listElement);

    }
    public void updatePost(Post post) {

        repo.save(post);
    }

    public void deletePost(int id) {
        repo.deleteById(id);
    }
}

Repository Interface

public interface PostRepository extends CrudRepository<Post, Integer> 
{      }

Application.properties file

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.studyeasy</groupId>
    <artifactId>06.01-RestfulMicroserviceWithDB</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>06.01-RestfulMicroserviceWithDB</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Outputs

when i perform get operation, out put was "[]"

 when i perform get operation by id , out put was 
 {
    "timestamp": "2019-03-29T02:44:00.768+0000",
     "status": 500,
     "error": "Internal Server Error",
    "message": "No value present",
    "path": "/posts/3" }
 java.util.NoSuchElementException: No value present

when i perform delete operation ,i got this output

"org.springframework.dao.EmptyResultDataAccessException: No class  org.studyeasy.entity.Post entity with id 3 exists!" in console and  

output in postman was

{ "timestamp": "2019-03-29T02:48:51.423+0000", "status": 500, "error": "Internal Server Error",
"message": "No class org.studyeasy.entity.Post entity with id 3 exists!",
"path": "/posts/3" }

Do as follows :

PostController.java

@RestController
public class PostController {

    @Autowired
    private PostsService service;

    @RequestMapping("/posts")
    public List<Post> getPosts(){
        return service.getPosts();
    }
    @RequestMapping("/posts/{id}")
    public Post getPost(@PathVariable int id) {
        return service.getPost(id);
    }

    @RequestMapping(method=RequestMethod.POST, value="/posts")
    public void addPost(@RequestBody Post listElement) {
        service.addPost(listElement);
    }

    @RequestMapping(method=RequestMethod.PUT, value="/posts/{id}")
    public void updatePost(@RequestBody Post post) {
        service.updatePost(post);
    }

    @RequestMapping(method=RequestMethod.DELETE, value="/posts/{id}")
    public void deletePost(@PathVariable int id) {
        service.deletePost(id);
    }
}

PostService.java

@Service
public class PostsService {
        @Autowired
        private PostRepository repo;     

       public List<Post> getPosts(){
            return (List<Post>) repo.findAll();
        }

        public Post getPost(int id) {
            return repo.findById(id).get();
        }

        public void addPost(Post listElement) {
            repo.save(listElement);

        }
        public void updatePost(Post post) {

            repo.save(post);
        }

        public void deletePost(int id) {
            repo.deleteById(id);
        }
    }

PostRepository.java

@Repository
public interface PostRepository extends CrudRepository<Post, Integer>{
}

Post.java

@Entity
@Table(name="posts")
public class Post implements Serializable{
    @Id
    @Column(name="id")
    int postId;
    @Column(name="title")
    String title;
    @Column(name="body")
    String body;

    public Post() {}
    public Post(int postId, String title, String body) {

        this.postId = postId;
        this.title = title;
        this.body = body;
    }
//gettters & setters
}

You can also refer Best Practice to send response for other stuffs. . .

Issue was you have missed @ResponseBody annotation. So here i have used @RestController

Output:

得到所有 GetById 创造

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