【发布时间】:2020-05-20 13:31:51
【问题描述】:
我有这个 JPA 类,其中有 3 列 id、name 和 date。数据库已经填充了数据,其中每个条目都有一个 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 而不是数据库中的字符串的任何想法? 我将非常感谢任何建议。
【问题讨论】:
-
不要调用 toString
new ResponseEntity<>(testDataJpaRecord, HttpStatus.OK); -
@AlanHay 不幸的是我收到了这个错误:`“异常”:“org.springframework.http.converter.HttpMessageNotWritableException”,“消息”:“无法编写 JSON:直接自引用导致循环; 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: Direct self-referenceleading to cycle`
标签: json spring-boot jpa get spring-data-jpa