Spring Data Jpa 自定义 Repository EntityManager is null

项目中升级了spring-data-jpa版本,发现继承了 QueryDslRepositorySupport 的自定义的Repository类一直报:

Caused by: java.lang.IllegalArgumentException: EntityManager must not be null!
    at org.springframework.util.Assert.notNull(Assert.java:134) ~[spring-core-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.jpa.repository.support.QueryDslRepositorySupport.validate(QueryDslRepositorySupport.java:75) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 23 common frames omitted

旧版本为: 1.11.4.RELEASE
新版本为: 1.11.8.RELEASE

对比源代码:
1.11.4:

    /**
     * Setter to inject {@link EntityManager}.
     * 
     * @param entityManager must not be {@literal null}
     */
    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {

        Assert.notNull(entityManager, "EntityManager must not be null!");
        this.querydsl = new Querydsl(entityManager, builder);
        this.entityManager = entityManager;
    }

1.11.8:

    /**
     * Setter to inject {@link EntityManager}.
     * 
     * @param entityManager must not be {@literal null}.
     */
    public void setEntityManager(EntityManager entityManager) {

        Assert.notNull(entityManager, "EntityManager must not be null!");
        this.querydsl = new Querydsl(entityManager, builder);
        this.entityManager = entityManager;
    }

新版本中去除了 @PersistenceContext 注解, 无法自动进行注入, 应该是新版本为了支持微服务, 表分库策略, 可以使用多个数据源, 多个EntityManager, 故移除自动注入, 改为手动注入:

@Autowired
    public CustomerRepositoryImpl(JpaContext context){
        super(Customer.class);
        setEntityManager(context.getEntityManagerByManagedType(Follow.class));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值