【发布时间】:2022-08-18 19:50:30
【问题描述】:
我正在使用 Spring Boot 应用程序构建 REST API。我已将应用程序连接到 Mongodb 数据库。我创建了一个名为 \"Employee\" 的数据库,并将集合作为 \"Employee\" 本身。现在我想创建一个文档。我有三个班。 A类、B类和C类。 A 类是具有属性(id、name、password)的父类。 B 类是子类,并用属性(地址,电话号码)扩展了 A 类,C 类是子类,它也用属性(父亲姓名,母亲姓名)扩展了 A 类。
现在我想将数据作为 B 的对象或 C 的对象添加到数据库中,并且还想从数据库中检索数据作为 B 的对象或 C 的对象。
这是A类的代码:
package com.example.webproject;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection=\"Employee\")
public class A {
@Id
private String id;
private String passwd;
private String username;
public String getId() {
return id;
}
public void setIp(String string) {
this.ip = string;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
B类:
package com.example.webproject;
public class B extends A {
private String address;
private String phoneNumber;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber= phoneNumber;
}
}
C类:
package com.example.webproject;
public class C extends A {
private String fatherName;
private String motherName;
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public String getMotherName() {
return motherName;
}
public void setMotherName(String motherName) {
this.motherName = motherName;
}
}
EmployeeRepository.java
package com.example.webproject;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends MongoRepository<A,String> {}
EmployeeController.java
@RestController
public class EmployeeController {
@Autowired
private EmployeeRepository repo;
@PostMapping(\"/addByB\")
public String addDataByB(@RequestBody B res) {
repo.save(res);
return \"added\";
}
@PostMapping(\"/addByC\")
public String addDataByC(@RequestBody C res) {
repo.save(res);
return \"added\";
}
@GetMapping(\"/getByB\")
public List<B> getDataByB(){
List<B> b= repo.findAll(); #Here it throws error because repo.findAll return object of A.
return b;
}
当我尝试使用 swagger 将数据添加为 B 对象或 C 对象时,数据将存储在数据库中。现在我想将数据检索为 B 对象或 C 对象,如何实现呢?
标签: spring spring-boot spring-data-mongodb mongorepository