Jpa 对多对多实现懒加载

Posted baizhuang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jpa 对多对多实现懒加载相关的知识,希望对你有一定的参考价值。

参考:https://www.jianshu.com/p/91d3096f38a0

实体:Device  与 Group 是多对多的关系

Group 维护端:

@Data
@Entity(name = "t_group")
public class Group extends BaseEntity
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "category_id",nullable = true)
    private int categoryId;
    //分组名
    private String name;

    @JsonIgnoreProperties(value = "groupList")
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "t_group_device",joinColumns = @JoinColumn(name = "group_id"),
            inverseJoinColumns = @JoinColumn(name = "device_id"))
    private List<Device> deviceList;

Device

@Data
@Entity(name = "t_device")
public class Device extends BaseEntity
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    //设备二级分类id
    @Column(nullable = true)
    private int categoryId;
    //设备源id
    @Column(nullable = true)
    private int sourceId;
    //设备名称
    private String name;
    //设备类型 1:实体设备  2:虚拟设备 3:系统设备
    @Column(nullable = true)
    private int type;
    //设备描述
    private String description;
    //设备实例化状态
    @Column(nullable = true)
    private int status;

    @JsonIgnoreProperties(value = "deviceList")
    @ManyToMany(mappedBy = "deviceList",fetch = FetchType.LAZY)
    private List<Group> groupList;

发现懒加载无法生效: 

1.添加依赖:

<dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-hibernate5</artifactId>
            <version>2.9.8</version>

</dependency>

2.yml 配置

spring:
    jpa:
        properties:
            hibernate:
                  enable_lazy_load_no_trans: true

3.添加配置文件

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer 

    /**
     * 解决jpa懒加载
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() 
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = converter.getObjectMapper();
        mapper.registerModule(hibernate5Module());
        return converter;
    

    @Bean
    public Hibernate5Module hibernate5Module() 
        Hibernate5Module module = new Hibernate5Module();
        module.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
        module.enable(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
        return module;
    

 

以上是关于Jpa 对多对多实现懒加载的主要内容,如果未能解决你的问题,请参考以下文章

jpa 关于懒加载的问题

解决hibernate中的懒加载(延迟加载)问题

Mybatis处理表关联(懒加载)

Hibernate—— 一对多 和 多对多关联关系映射(xml和注解)总结(转载)

JPA 懒加载问题

Hibernate检索学习