我有这个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而不是从数据库返回为字符串的任何想法?我非常感谢您的任何建议。
如果您在类路径上有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);
}
参见: