在spring-boot应用程序中将父类的对象检索到子类中



我正在使用弹簧引导应用程序构建REST API。我已经将应用程序连接到Mongodb数据库。我创建了一个名为";"雇员";并且集合为";"雇员";它本身现在我想创建一个文档。我有三节课。A类、B类和C类。类A是具有属性(id、名称、密码(的父类。类B是子类,并用属性(address,phoneNumber(扩展了类A,类C是也用属性(parentName,MotherName(扩展了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对象,如何实现这一点?

因为你只创建了类A的Repository并调用它,所以你必须创建另两个类B和C的repo,然后像调用"EmployeeRepository;这样你就可以使用它们并获取数据。

最新更新