当前位置: 首页 > 面试题库 >

Spring Rest lazy hibernate

徐高懿
2023-03-14
问题内容

我正在尝试使用Hibernate开发Spring Rest API。在谷歌搜索后,我没有找到延迟加载的解决方案。我有两个实体,如下所示:

大学

@Entity()
@Table(schema = "core", name = "university")
public class University extends BaseEntity {

    private String uniName;
    private String uniTelephon;


    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "university", cascade = CascadeType.ALL)
    @JsonManagedReference
    private List<Student> students;

//setter and getter
}

学生.java

@Entity
@Table(schema = "core",name = "student")
public class Student {

    @Id
    @GeneratedValue            
    private long id;

    private String firstName;

    private String lastName;

    private String section;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "UNIVERSITY_ID",nullable = false)
    @JsonBackReference
    private University university;
    // setter and getter
}

我休息的任何终点

@GetMapping("/list")
public ResponseEntity list() throws Exception {
    // I need to return just Universities But it return it eagerly with their students
    return new ResponseEntity(this.universityService.findAll(), HttpStatus.OK);
}

调用其余的api后,它将与所有学生一起返回大学。

有一种方法告诉杰克逊不要序列化未提取的对象或集合?

有人可以为我提供可靠的解决方案吗?


问题答案:

尝试添加以下依赖项(取决于您的hibernate版本):

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>${jackson.version}</version>
</dependency>

然后(假设您具有基于Java的配置)在WebMvcConfigurerAdapter类中添加以下内容:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(jackson2HttpMessageConverter());
}

@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(this.jacksonBuilder().build());

    return converter;
}

public Jackson2ObjectMapperBuilder jacksonBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

    Hibernate5Module hibernateModule = new Hibernate5Module();

    hibernateModule.configure(Feature.FORCE_LAZY_LOADING, false);

    builder.modules(hibernateModule);

    // Spring MVC default Objectmapper configuration
    builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    builder.featuresToDisable(MapperFeature.DEFAULT_VIEW_INCLUSION);

    return builder;
}

它应该强制Jackson的objectMapper不获取延迟加载的值。



 类似资料:

相关阅读

相关文章

相关问答