无法使用spring数据jpa保留子类记录

时间:2018-02-26 06:44:30

标签: spring-boot spring-data spring-data-jpa

问题

1)我创建了一个扩展Person的班级员工。我可以保留员工记录,而不是人员。

解决方案我已实施

1)创建模态类Employee and Person。

模态类

员工

@Entity
@Table(name = "employee",
    indexes = {@Index(name = "username", columnList = "username", unique = true)})
public class BaseEmployee extends Person {

public static final String OBJECT_KEY = "EMPLOYEE";
@Id
@GeneratedValue
private Long id;
// Who created this baseEmployee
private String userId;
//    @Indexed(unique = true)
private String username;
@Enumerated(EnumType.STRING)
private ROLE role;
@Enumerated(EnumType.STRING)
private STATUS status;
private String designation;

public class Person extends AbstractEntity {
private String firstName;
private String lastName;
private String contact;
private String email;
@Enumerated(EnumType.STRING)
private GENDER gender;
private String imageId;
private String address;
private String locationId;
private DateTime dob;
private double[] location;
private String pinCode;

员工控制器

@PostMapping
ApiResponse<BaseEmployee> post(@RequestBody CreateEntry<BaseEmployee> baseEmployeeCreateEntry) {
    BaseEmployee baseEmployeeToCreate = baseEmployeeCreateEntry.getEntry();
    baseEmployeeToCreate.setStatus(STATUS.ACTIVE);
    baseEmployeeToCreate = employeeService.post(baseEmployeeToCreate);
    if (baseEmployeeToCreate != null)
        authenticationService.setPassword(baseEmployeeToCreate, baseEmployeeCreateEntry.getPassword());
    return ApiResponse.success().message("Created Successfully!").object(baseEmployeeToCreate);
}

public class CreateEntry<T> {
private T entry;
private String password;

服务

@Override
public <E extends BaseEmployee> E post(E employee) {
    employee = employeeRepository.save(employee);
    System.out.println(employee);
    LOG.info("Admin data" + employee);
    LOG.info("PUT employee {} {} {}", employee.getId(), employee.getFirstName(), employee.getEmail());
    return employee;
}

存储库

public interface EmployeeRepository extends JpaRepository<BaseEmployee, Long> {}

#Expected Output
 The Employee class Columns and Person class Columns

#Output Shown

mysql> select * from employee;

 id | created_at    | created_by    | last_modified_at | last_modified_by | version | designation | role  | status | user_id | username |

  1 | 1519624346694 | anonymousUser |    1519624346694 | anonymousUser    |       0 | csdcs       | ADMIN | ACTIVE | string  | admin    |
  3 | 1519624856504 | anonymousUser |    1519624856504 | anonymousUser    |       0 | csdcs       | ADMIN | ACTIVE | string  | admin1   |
  4 | 1519626598478 | anonymousUser |    1519626598478 | anonymousUser    |       0 | csdcs       | ADMIN | ACTIVE | string  | admin2   |
  

任何人都可以指导我做错了什么。提前谢谢你?

1 个答案:

答案 0 :(得分:0)

您可以尝试将@MappedSuperclass添加到Person实体吗?