Springcloud + jpa 做两个一对多关联时报错:
代码:
//===========================表关联==================================== //一个product(商品)对应多个deputyPicture(副图) @OneToMany(targetEntity = PointsMallDeputyPicture.class, fetch = FetchType.EAGER) @JoinColumn( name = "product_id", referencedColumnName = "id", insertable = false, updatable = false, foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT) ) @NotFound(action = NotFoundAction.IGNORE) private List<PointsMallDeputyPicture> pointsMallDeputyPictureList; //一个product(商品)对应多个productSku(规格) @OneToMany(targetEntity = PointsMallProductSku.class, fetch = FetchType.EAGER) @JoinColumn( name = "product_id", referencedColumnName = "id", insertable = false, updatable = false, foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT) ) @NotFound(action = NotFoundAction.IGNORE) private List<PointsMallProductSku> pointsMallProductSkuList;
Error: 无法同时获取多个包:[cn.shencom.model.PointsMallProduct.pointsMallDeputyPictureList,cn.shencom.model.PointsMallProduct.pointsMallProductSkuList];
2019-01-03 11:27:18.397 WARN [service-points-mall,,,] 11236 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [cn/shencom/scloud/common/hibernate/MultiTenancyJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: tenantdb-persistence-unit] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [cn.shencom.model.PointsMallProduct.pointsMallDeputyPictureList, cn.shencom.model.PointsMallProduct.pointsMallProductSkuList]
解决方法:在看了其他人做的同样的两个一对多关联,却没有报错,原因是 fetch = FetchType.EAGER 只能有一个是立即加载(EAGER);需将另一个该为延迟加载:fetch = FetchType.LAZY