问题:
Spring在mongodb中创建了两个集合,分别是超类雇员姓名和基类经理和主管。 我想在春季之前阻止在mongo db中为超类员工创建集合我正在使用Spring-boot JPA mongodb maven插件。
我试图仅使用一个通用存储库和相同的超级实体类在mongo collection Manager和超级用户上执行插入操作。
manager
{
id:"abc",
name:"Deva",
age:26
}
supervisor
{
id:"abc",
name:"Raj",
age:25
}
这是我的雇员班,是超级班,将由我的经理和主管班扩展
public @Data class Employee
{
private String id;
private String name;
private int age;
}
Manager类绑定到集合管理器
@JsonInclude(JsonInclude.Include.NON_NULL)
@Document(collection="manager")
public @Data class Manager extends Employee
{
}
主管类绑定到集合主管
@JsonInclude(JsonInclude.Include.NON_NULL)
@Document(collection="supervisor")
public @Data class Supervisor extends Employee
{
}
使用一种save()方法将通用接口实现以将文档保存到集合中
public interface EmployeeService<T>
{
public T save(T employee);
}
@Service
public class EmployeeServiceImpl<T> implements EmployeeService<T>
{
@Autowired
EmployeeRepository employeeRepository;
@Override
public T save(T obj) {
return (T) employeeRepository.save(obj);
}
}
我已经创建了一个存储库EmployeeRepository,它是通用的,可用于经理和主管实体集合文档。
public interface EmployeeRepository<T extends Employee> extends MongoRepository<T, String> {
{
}
这是我的组件,它将调用以保存经理或主管mongo集合中的雇员。
@Component
public class EmployeeComponent<T>
{
@Autowired
EmployeeService employeeService;
private boolean updateEmployee(Employee employee) throws Exception
{
Employee employees= employeeService.save(employee);
if (employees.isEmpty())
{
System.out.println("Failed to save employees.");
return "Failed to save employees.";
}
else
{
System.out.println("Success.");
return "Success.";
}
}
}
这是我的控制器调用保存功能并根据条件传递的员工或主管对象
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
EmployeeComponent<?> employeeComponent;
@Autowired
ObjectMapper mapper;
@RequestMapping(value="save/employee", method=RequestMethod.POST)
public ResponseEntity<String> updateEmployee(@RequestBody String employeeString) throws ParseException, Exception
{
try
{
Employee emp;
boolean isEmployeeManager = true;
> //Logic to convert string to class obj using ObjectMapper;
if(isEmployeeManager)
{
emp = mapper.readValue(employeeString, Manager.class);
}
else
{
emp = mapper.readValue(employeeString, Supervisor.class);
}
return employeeComponent.updateEmployee(emp);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}