如何在findAll和findOne存储库方法上使用不同的EntityGraph作为注释

时间:2015-08-12 20:52:05

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

我有一个Spring项目,它使用Hibernate与底层MySQL数据库进行交互。请注意,EHCACHE用作Hibernate二级缓存。

我试图通过在findAll和fineOne方法上使用不同的@EntityGraph注释来加载不同的依赖对象。我首先使用findAll方法加载实体,然后使用findOne方法加载相同的对象 - 令我惊讶的是,它只是忽略了findOne方法上指定的@EntityGraph,而是使用findAll上指定的EntityGraph返回数据。

为了更好地解释这个问题,我正在复制下面的实体类和存储库类:

@Entity
@Table(name = "COURSE")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName="course")
@NamedEntityGraphs({
    @NamedEntityGraph(name = "categories", attributeNodes = @NamedAttributeNode("categories")),
    @NamedEntityGraph(name = "batches", attributeNodes = @NamedAttributeNode("batches"))
})
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")

public class Course implements Serializable {

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

    @OneToMany(mappedBy = "course")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Batch> batches = new HashSet<>();

    @ManyToMany
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JoinTable(name = "COURSE_CATEGORY",
               joinColumns = @JoinColumn(name="courses_id", referencedColumnName="ID"),
               inverseJoinColumns = @JoinColumn(name="categorys_id", referencedColumnName="ID"))
    private Set<Category> categories = new HashSet<>();

    // GETTERS AND SETTERS
}

存储库类是:

public interface CourseRepository extends JpaRepository<Course,Long> {

    @EntityGraph(value = "categories", type = EntityGraphType.FETCH)
    Page<Course> findAll(Pageable pageable);

    @EntityGraph(value = "batches", type = EntityGraphType.FETCH)
    Course findByIdAndPublished(Long id);

}

加载后,调用以这种格式发生:

  • courseRepository.findAll()=&gt;这将加载并返回加载了类别的所有Course对象
  • courseRepository.findOne(1)=&gt;这将返回ID为1的课程但是再次加载类别而不是批次(请注意,根据EntityGraph,我希望加载批次而不是类别)

提前感谢您的帮助, ANKIT

0 个答案:

没有答案