【问题标题】:calculated fields in Entity: Autowired is null实体中的计算字段:Autowired 为空
【发布时间】:2015-11-18 10:24:19
【问题描述】:

我有一个Entity

@Entity
@Table(name = "orgtree")
public class OrganizationTree {

    @Id
    @Column(name="ORGANIZATION_ID")
    private String organizationId;

    @Column(name="ORGANIZATION_NAME")
    private String organizationName;

}

以及提供 REST 访问的存储库

@RepositoryRestResource(collectionResourceRel = "organizationTree", path = "organizationTree")
public interface OrganizationTreeRepository extends JpaRepository<OrganizationTree,String> {
    @Query
    @RestResource(path = "findAll", rel = "findAll")
    List<OrganizationTree> findAll();
}

到目前为止一切顺利。

现在我想向我的实体添加一个计算字段

@Autowired
@Transient
private OrgTreeService orgTreeService;

@JsonSerialize
public Integer getPersonCount() {
    return orgTreeService.getPersonCount(organizationId);
}

这里我有几个问题:

  • orgTreeService 为空
  • 人们说使用 实体中的服务

这个问题的典型解决方案是什么?

【问题讨论】:

    标签: spring hibernate spring-boot


    【解决方案1】:

    我找到的一个解决方案(或者我应该称之为 hack)如下:

    我使用自定义序列化程序注释计算字段:

    @Formula(value = "ORGANIZATION_ID")
    @JsonSerialize(using=JsonOrgPersonCountSerializer.class)
    private String personCount;
    

    在序列化程序中,我计算人员的数量:

    public class JsonOrgPersonCountSerializer extends JsonSerializer<String> {
    
        @Override
        public void serialize(String source, JsonGenerator gen, SerializerProvider prov) throws IOException, JsonProcessingException {
            gen.writeString("" + orgTreeService.getPersonCount(source));
        }
    
    }
    

    另一种解决方案是使用某种数据传输对象,我可以在其中调用我的服务。

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多