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

标签 java mysql hibernate rest spring-boot-jpa

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.

我的应用程序类

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

Controller 类

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

存储库接口(interface)

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>

输出

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

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

"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" }

最佳答案

执行如下操作:

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

关于java - findAll() 在 SpringBoot Rest MySql CRUD 操作应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55409875/

相关文章:

Java - 索引越界异常 : Index: 1, 大小:2

mysql - Solr 以几个较小的 block 完全导入

java - 如何进行 Hibernate XML 映射,一对多使用 1 PK 映射到具有复合键的另一个实体

java - Spring 数据和 hibernate 比存储过程更快

java - 在 Java JSch Shell 中获得两次 shell 提示符

java - Eclipse RCP 右键单击​​事件

java - 1怎么大于4?

php - Mysql distinct with count with 条件

mysql - SQL异常 : Access denied in Spring Boot

java - 覆盖hibernate子类中的主键