使用JDK17 + Spring Boot 3.0 + JPA + QueryDsl来构建一个restful的服务
定义了一个实体
@Entity
public class User{
//略
}
一个jpa的默认repo实现
@Repository
public interface UserRepository extends JpaRepository<User, UUID>, UserRepoCustom {
//略
}
一个基于querydsl实现的自定义repo,就是上面代码中的userRepoCustom
public interface UserRepoCustom {
void test();
}
public class UserRepoCustomImpl {
@PersistenceContext
private EntityManager entityManager;
private final JPAQueryFactory queryFactory;
public UserRepoCustomImpl () {
this.queryFactory=new JPAQueryFactory(this.entityManager);
}
@Override
public void test(){
queryFactory.from.略
}
}
实际使用的时候,会报错
java.lang.NullPointerException: Cannot invoke "jakarta.persistence.EntityManager.getDelegate()" because "em" is null
提示是找不到entitymanager,导致querydsl的查询工厂初始化失败,无法进行后续的查询
解决方法如下:
改造自定义repo的实现,修改entitymanger的获取方式
public class UserRepoCustomImpl {
private EntityManager entityManager;
private final JPAQueryFactory queryFactory;
public UserRepoCustomImpl (JpaContext jpaContext) {
//从jpa上下文指定获取user的em,而不是让他自动装配
this.entityManager =jpaContext.getEntityManagerByManagedType(user.class);
this.queryFactory=new JPAQueryFactory(this.entityManager);
}
//略
}
}
标签:em,getDelegate,EntityManager,entityManager,queryFactory,public,JPAQueryFactory
From: https://www.cnblogs.com/tilv37/p/17215430.html