【问题标题】:findAll() is not working in SpringBoot Rest MySql CRUD operations applicationfindAll() 在 SpringBoot Rest MySql CRUD 操作应用程序中不起作用
【发布时间】:2019-08-19 22:46:10
【问题描述】:

我正在尝试使用 spring boot+REST+MySQL 执行 CRUD 操作 沿着 crudrepository 接口,当我尝试从数据库中获取数据时,我 正在返回空列表。我发现我的应用程序中的 findAll() 方法没有按预期工作。

我的应用类

@SpringBootApplication
public class Blog {

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

我的实体类

@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()

控制器类

@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
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);
    }
}

存储库接口

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

Application.properties 文件

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>

输出

当我执行get操作时,输出的是“[]”

 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

当我执行删除操作时,我得到了这个输出

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

邮递员的输出是

{ "时间戳": "2019-03-29T02:48:51.423+0000", “状态”:500, "error": "内部服务器错误",
"message": "没有类 org.studyeasy.entity.Post 具有 id 的实体 3 存在!",
“路径”:“/posts/3”}

【问题讨论】:

    标签: java mysql hibernate rest spring-boot-jpa


    【解决方案1】:

    按如下操作:

    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
    }
    

    您也可以参考Best Practice to send response 了解其他内容。 . .

    问题是您错过了@ResponseBody 注释。所以这里我使用了@RestController

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多