【问题标题】:How to ignore LAZY types dynamically on SpringBoot app?如何在 Spring Boot 应用程序中动态忽略 LAZY 类型?
【发布时间】:2020-05-04 20:27:49
【问题描述】:

我有一堂课:

@Entity
@Table(name = "restaurants")
public class Restaurant extends AbstractNamedEntity implements Serializable {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "restaurant")
    private Set<Meal> meals = Collections.emptySet();

    //other fields, getters, setters, constructors
}

我正在使用 Spring Data 获取数据:

@Repository
public interface RestaurantRepository extends CrudRepository<Restaurant, Integer> {

}

我有 REST 控制器,它产生 JSON 数据:

@RestController
@RequestMapping(value = RestaurantController.REST_URL, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public class RestaurantController {
    static final String REST_URL = "/restaurants";

    @Autowired
    private RestaurantRepository repository;

    @GetMapping("{id}")
    public List<Restaurant> getOne(@PathVariable Integer id) {
        return repository.findById(id);
    }
}

如何避免包含那些 LAZY 数据(一组膳食)以将它们发送到 SQL 请求? 据我所知,我需要编写一个自定义 JacksonObjectMapper,但我不知道该怎么做

【问题讨论】:

    标签: java hibernate spring-boot spring-data


    【解决方案1】:

    您可以使用@JsonIgnore 注释来忽略字段的映射。那么你应该这样做:

    @JsonIgnore
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "restaurant")
    private Set<Meal> meals = Collections.emptySet();
    

    更新

    根据您想要执行的操作“获取一个或不获取所有时动态忽略字段”您可以使用@NamedEntityGraphs 注释来指定您想要加入的字段,然后使用@NamedEntityGraph您指定查找操作或查询的路径和边界,并且您应该在您的自定义 Repository 中使用 @EntityGraph 注释,该注释允许根据您想要执行的操作自定义 fetch-graph

    所以你应该添加以下代码:

    @Entity
    @Table(name = "restaurants")
    @NamedEntityGraphs({
        @NamedEntityGraph(name="Restaurant.allJoins", includeAllAttributes = true),
        @NamedEntityGraph(name="Restaurant.noJoins")
    })
    public class Restaurant extends AbstractNamedEntity implements Serializable {
    
    }
    
    @Repository
    public interface RestaurantRepository extends CrudRepository<Restaurant, Integer> {
    
        @EntityGraph(value = "Restaurant.allJoins", type = EntityGraphType.FETCH)
        @Override
        List<Restaurant> findAll();
    
        @EntityGraph(value = "Restaurant.noJoins", type = EntityGraphType.FETCH)
        @Override
        Optional<Restaurant> findById(Integer id);
    
    }
    

    【讨论】:

    • 我需要忽略序列化,而不是视图
    • 是的,您将使用该注释进行操作。
    • 有时我需要把它们放在一起。该注释没有给出它
    • 你的意思是动态忽略序列化吗?让我知道您何时愿意忽略,何时不想忽略。
    • 好的,我会更新我的答案,然后使用其他注释。
    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 2017-03-31
    • 2019-12-11
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2023-03-16
    相关资源
    最近更新 更多