findAll()在SpringBoot Rest MySql CRUD操作应用程序中不起作用

时间:2019-03-29 02:59:36

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

  

我正在尝试使用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  
  

邮递员的输出是

     

{“ timestamp”:“ 2019-03-29T02:48:51.423 + 0000”,            “状态”:500,             “错误”:“内部服务器错误”,
           “ message”:“没有ID为org.studyeasy.entity.Post的类的实体                       3存在!“,
              “ path”:“ / posts / 3”}

1 个答案:

答案 0 :(得分:0)

执行以下操作:

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

输出:

GetAll GetById Create