how to create JPAQueryFactory correctly with QueryDsl

Viewed 566

I heard about EntityManager is not thread-safe, so we use @PersistenceContext instead of @Autowired.

However, I found about two ways to create JPAQueryFactory on the Internet.

  1. define a bean like this
@Configuration
public class JPAQueryFactoryConfiguration {
    
    @Bean
    public JPAQueryFactory jpaQueryFactory(@Autowired EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }
}
  1. @PersistenceContext on EntityManager ,new JPAQueryFactory(entityManager) every time
@Service
public class TestServiceImpl implements TestService {
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void test(){
        JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(entityManager);
        xxxxxxxxxxxx
    }
}

I'm counfused. But, I think the first way is not correct according to the difference between @PersistenceContext and @Autowired

2 Answers

i am just biginer in EJB , type of JPAQueryFactory is Provider is not EntityManager , just Cast

JPAQueryFactory query = new JPAQueryFactory((Provider<EntityManager>) em);

or use the declaration of JPAQueryFactory

EntityManagerFactory emf = 
  Persistence.createEntityManagerFactory("com.baeldung.querydsl.intro");
EntityManager em = entityManagerFactory.createEntityManager();
JPAQueryFactory queryFactory = new JPAQueryFactory(em);

As this article shows, you need to use both the entity manager and JPAQueryFactory as follows:

Extend SimpleJpaRepository and implement BaseRepository

  • BaseRepository is an interface that extends JpaRepository
public abstract class BaseRepositoryImpl<T, ID> 
        extends SimpleJpaRepository<T, ID> 
        implements BaseRepository<T, ID> {   
     
    EntityManager em;
    JPAQueryFactory queryFactory;
        
    public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
        this.em = em;
        this.queryFactory = new JPAQueryFactory(em);
    }
}

and create a class that extends your BaseRepositoryImpl to use JPAQueryFactory in it.

Related