【问题标题】:Spring REST Repositories inheritance null valuesSpring REST Repositories 继承空值
【发布时间】:2018-12-11 22:17:23
【问题描述】:

我在 Spring Rest 存储库中映射父子类时遇到了一些问题。我的情况是我需要使用 Spring Security 对两种类型的用户进行身份验证,但我还希望能够将类型特定的属性分配给所有者,例如将宠物分配给所有者,并分配给员工的薪水。是实现这一目标的良好结构吗?如果是这样,请帮助解决这个问题。

我已经使用 dtype 列将其插入到一个表中,以区分彼此,但无法插入除 dtype 之外的任何其他值。

我正在使用最新的带有 MS SQL 的 Spring Boot(默认 JSON 映射器)。

这是我的 POST 请求负载:

{
    "username": "admin",  // null in db
    "firstName": "Delacruz", // null in db
    "lastName": "House", // null in db
    "dtype": "Owner" // present in db
}

这是我的班级结构:
存储库

@RepositoryRestResource(path = "user", collectionResourceRel = "user")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}

父类 - 用户

@Entity
@Table(name = "users")
@Inheritance
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
        include=JsonTypeInfo.As.EXISTING_PROPERTY,
        property="dtype")
@JsonSubTypes({
        @JsonSubTypes.Type(name="Owner", value=Owner.class),
        @JsonSubTypes.Type(name="Employee", value=Employee.class)})
@RestResource(path="user")
public abstract class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String username;
// rest of properties
}

员工 - 第一个子类

@EqualsAndHashCode(callSuper = true)
@Entity
@Data
public class Employee extends User {

    private String type = "EMPLOYEE";

    @Column
    @Enumerated
    private EmployeeType employeeType;

    @Column
    private LocalDate dateOfEmployment;
    //rest of properties
}

所有者 - 另一个子类

@EqualsAndHashCode(callSuper = true)
@Data
@Entity
public class Owner extends User{
    @OneToMany(mappedBy = "owner")
    private List<Pet> pets;
}

【问题讨论】:

    标签: java spring jackson spring-data-jpa spring-rest


    【解决方案1】:

    将以下构造函数(根据所有者)添加到子类已解决的问题:

    @JsonCreator
    public Employee(
            @JsonProperty(value = "username") String username,
            @JsonProperty(value = "firstName") String firstName,
            @JsonProperty(value = "lastName") String lastName,
            @JsonProperty(value = "password") String password,
            @JsonProperty(value = "email") String email,
            @JsonProperty(value = "phoneNumber") String phoneNumber
    ) {
        super(username, firstName, lastName, password, email, phoneNumber);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-16
      • 1970-01-01
      • 2014-10-16
      • 2015-02-07
      • 2020-01-15
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      相关资源
      最近更新 更多