EntityGraph从实体返回所有内容

时间:2019-04-01 18:17:10

标签: java spring hibernate entitygraph

我的实体Citizen有一个WeeklyCare的列表。每个WeeklyCare都有一个SubCategoryCare的列表。我有一个使用CrudRepository获取所有公民的Web服务。我想要的是从每个SubCategoryCare的每个WeeklyCare中排除Citizen。有人告诉我可以使用EntityGraph来完成此操作,但是我无法使其正常工作。

这是我的CitizenEntityGraph

@Entity
@Table(name = "citizens")
@NamedEntityGraph(
    name = "Citizen.noSubCategoryCare",
    attributeNodes = {
            @NamedAttributeNode("cpr"),
            @NamedAttributeNode("name"),
            @NamedAttributeNode("section"),
            @NamedAttributeNode(value = "weeklyCare", subgraph = "weeklyCareSubgraph"),
    },
    subgraphs = {
            @NamedSubgraph(
                    name = "weeklyCareSubgraph",
                    attributeNodes = {
                            @NamedAttributeNode("id"),
                            @NamedAttributeNode("week"),
                            @NamedAttributeNode("year"),
                            @NamedAttributeNode("practicalCare"),
                            @NamedAttributeNode("personalCare"),
                            @NamedAttributeNode("healthCare"),
                            @NamedAttributeNode("rehabilitation"),
                            @NamedAttributeNode("totalCare"),
                            @NamedAttributeNode("hospitalized"),
                            @NamedAttributeNode("citizenId"),
                    }
            )
    }
)
public class Citizen {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NaturalId
@Size(max = 10, min = 10, message = "CPR must be exactly 10 characters")
private String cpr;

@NotNull
private String name;

@NotNull
private String section;

@OneToMany(mappedBy = "citizen", cascade = CascadeType.ALL, orphanRemoval = true)
private List<WeeklyCare> weeklyCare;
}

这是我的CrudRepository

public interface CitizenRepository extends CrudRepository<Citizen, Long>{

@EntityGraph(value = "Citizen.noSubCategoryCare", type = EntityGraph.EntityGraphType.FETCH)
@Query("SELECT c FROM Citizen c")
List<Citizen> findAllWithoutSubCategoryCare();

@EntityGraph(value = "Citizen.noSubCategoryCare", type = EntityGraph.EntityGraphType.FETCH)
Citizen findByCpr(String cpr);
}

在返回公民的Controller中,我正在执行以下操作:

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping(path = "/all") // Map ONLY GET Requests
public @ResponseBody
Iterable<Citizen> getAllCitizens() {
    Citizen c = citizenRepository.findByCpr("someCpr");
    Iterable<Citizen> cc2 = citizenRepository.findAllWithoutSubCategoryCare();
    return cc2;
}

两种方法都返回包含每个属性的公民。我在做什么错了?

0 个答案:

没有答案