0

我正在尝试使用 spring boot+REST+MySQL 沿着 crudrepository 接口执行 CRUD 操作,当我尝试从数据库中获取数据时,我得到的是空列表。我发现我的应用程序中的 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", "status": 500, "error": "Internal Server Error",
"message": "No class org.studyeasy.entity.Post 实体id 3 存在!",
"path": "/posts/3" }

4

1 回答 1

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
}

您还可以参考最佳实践来发送其他内容的响应。. .

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

输出:

得到所有 GetById 创造

于 2019-05-03T10:32:25.803 回答