即使使用FetchType.EAGER设置,Spring也不会加载数据

时间:2016-10-17 19:57:54

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

我有两个模型,我试图从REST API(宠物和媒体)获取数据。我试图通过FetchType.EAGER注释急切地加载宠物和媒体之间的oneToMany关系,但是当我编写MediaRepository时数据不会出现。如果我没有实现该文件,则媒体关系和数据会在响应中返回。

使用MediaRepository.java实现,GET / pets返回:

{
  "id": 72,
  "name": "Spot",
  "description": "Annoying as hell",
  "media": [], <-- why is this here only if I don't implement MediaRepository?
  ...
}

没有MediaRepository.java已实现,GET / pets返回:

{
  "id": 72,
  "name": "Spot",
  "description": "Annoying as hell",
  ... (No media array in response)
}

Pet.java

@Entity
public class Pet implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @Column(name="description")
    private String description;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="pet", FetchType.EAGER, orphanRemoval=true)
    private List<Media> media;

    @ManyToOne
    private Category category;

    @Enumerated(EnumType.STRING)
    private Status status;
}

Media.java

@Entity
public class Media implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name="url")
    private String url;

    @Column(name="title")
    private String title;

    @ManyToOne
    private Pet pet;
}

PetRepository.java

import org.springframework.data.jpa.repository.JpaRepository;

public interface PetRepository extends JpaRepository<Pet, Long> {
}

MediaRepository.java

import org.springframework.data.jpa.repository.JpaRepository;

public interface MediaRepository extends JpaRepository<Media, Long> {
}

1 个答案:

答案 0 :(得分:5)

这与Hibernate获取策略无关。

您所看到的行为是Spring Data Rest的工作原理。为媒体定义存储库后,您将看到响应中提供了一个链接,以便客户端检索关联的媒体项。如果没有存储库,则必须在响应中包含关联,因为当然没有办法独立检索集合。

如果您希望在响应中有选择地插入集合,则可以通过定义投影来完成。

@Projection(name = "inlineData", types=Pet.class)
public interface PetProjection{

    Long getId();
    String getName();
    String getDescription();
    List<Media> getMedia();
}

您可以将此投影自动应用于集合资源:

@RepositoryRestResource(excerptProjection = PetProjection.class)
public interface PetRepository extends JpaRepository<Pet, Long> {}

对于项目资源,客户通常会指定他们希望这些数据在线:

e.g。

http://example.com/api/pets/1?projection=inlineData

http://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts