如何从数据库存储库获取JSON格式的数据

问题描述 投票:0回答:1

我有这个JPA类,其中有3列idnamedate。数据库已经充满了数据,其中每个条目都有一个ID。

@Data
@Entity
@Table(name = "TEST", schema = "TESTSCHEMA")
public class TestDataJpaRecord implements Serializable {
    private static final long serialVersionUID = 1L;

    TestDataJpaRecord(){
        // default constructor
    }

    public TestDataJpaRecord(
       String name,
       Date date,
    ){
        this.name = name;
        this.date = date;
    }

    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = "TEST_SEQUENCE")
    @SequenceGenerator(
            sequenceName = "TEST_SEQUENCE", allocationSize = 1,
            name = "TEST_SEQUENCEx")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "DATE")
    private Date date;
}

我为所有数据创建了一个JPA存储库。

public interface TestDataJpaRecordRepository extends JpaRepository<TestDataJpaRecord, Long> {
}

我想以JSON格式从数据库获取数据。这是我的REST GET Api。在这里,我只是以字符串形式返回数据,但我想以JSON形式返回它们。

@GetMapping(value = "data/{id}")
    private ResponseEntity<?> getDataFromTheDB(@PathVariable("id") Long id) {

        // get one entry form the DB
        TestDataJpaRecord testDataJpaRecord =testDataJpaRecordRepository.findOne(id); 

        // Here I want to return a JSON instead of a String 
        return new ResponseEntity<>(testDataJpaRecord.toString(), HttpStatus.OK);
    }

关于如何将数据作为JSON而不是从数据库返回为字符串的任何想法?我非常感谢您的任何建议。

json spring-boot jpa get spring-data-jpa
1个回答
0
投票

如果您在类路径上有Jackson,如果您使用过spring-boot-starter-web,那么应该这样做:

@GetMapping(value = "data/{id}")
private ResponseEntity<TestDataJpaRecord> getDataFromTheDB(@PathVariable("id") Long id) {
    TestDataJpaRecord testDataJpaRecord =testDataJpaRecordRepository.findOne(id); 
    return new ResponseEntity.ok(testDataJpaRecord);
}

这是假设您用@RestController而不是@Controller注释了控制器。如果不是,则可以执行此操作,也可以用@ResponseBody注释控制器方法。

启用Spring Data的Web支持(默认情况下,在Spring Boot中应启用它,然后您还可以简化如下:

@GetMapping(value = "data/{id}")
private ResponseEntity<TestDataJpaRecord> 
         getDataFromTheDB(@PathVariable("id") TestDataJpaRecord record) {
    return new ResponseEntity.ok(record);
}

参见:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web.basic.domain-class-converter

© www.soinside.com 2019 - 2024. All rights reserved.