如何使用jpa在json中检索我的外键字段值?

时间:2019-07-04 09:39:10

标签: json spring hibernate jpa

我有一个包含某些实体的数据库,当我尝试进行查询并以JSON数组获取数据时,我只会获取不是外键的字段,而那些是外键的字段会显示在链接中。     如何正常获取外键字段?

这是我的模型课:

@Table(name = "affecter")
@Data
@Entity
public class Affecter implements Serializable {
  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", insertable = false, nullable = false)
  private Integer id;

  @Column(name = "dateEntree", nullable = false)
  private Date dateEntree;

  @Column(name = "dateSortie")
  private Date dateSortie;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="idAffaire", nullable = false)
  @JsonBackReference
  private Affaire affaire;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="idService", nullable = false)
  @JsonBackReference
  private Service service;

这是我的存储库:

@CrossOrigin("*")
@RepositoryRestResource
public interface AffecterRepository extends JpaRepository<Affecter, Integer>, JpaSpecificationExecutor<Affecter>{
    //Long countById();


    @Query(value = "SELECT a FROM Affecter a WHERE a.service.id = ?1 AND a.dateSortie=null")
    @RestResource(path = "/byService")
    public List<Affecter> findAffecterByService(@Param("idS") Integer service);

}

这是链接返回的我的JSON数组:http://localhost:8080/affecters

id: 2,
dateEntree: "2019-06-19T00:00:00.000+0000",
dateSortie: null,
_links: {
self: {
href: "http://localhost:8080/affecters/2"
},
affecter: {
href: "http://localhost:8080/affecters/2"
},
affaire: {
href: "http://localhost:8080/affecters/2/affaire"
},
service: {
href: "http://localhost:8080/affecters/2/service"
}
}

1 个答案:

答案 0 :(得分:0)

您还必须将外键列映射为实体中的属性,但必须是只读的:

@Column(name = "idAffaire", insertable = false, nullable = false)
private Integer idAffaire;

@Column(name = "idService", insertable = false, nullable = false)
private Integer idService;