参考: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; } }
原文地址:https://www.cnblogs.com/baizhuang/p/11057918.html
时间: 2024-11-09 04:54:06