当不能直接提取时,我们可以考虑JPQL / HQL查询提取。
本文的应用程序展示如何通过JpaRepository,EntityManager和Session实现查询概念的证明。
关键点:
源代码可以在 这里 找到
JpaRepository:
@Repository <b>public</b> <b>interface</b> UserRepository <b>extends</b> JpaRepository<User, Long> { @Transactional(readOnly = <b>true</b>) List<User> findByName(String name); @Transactional(readOnly = <b>true</b>) @Query(<font>"select u from User u where u.name = ?1"</font><font>) List<User> fetchUsersByName(String name); } </font>
@Repository @Transactional(readOnly = <b>true</b>) <b>public</b> <b>class</b> Dao<T, ID <b>extends</b> Serializable> implements GenericDao<T, ID> { @PersistenceContext <b>private</b> EntityManager entityManager; @Override <b>public</b> List<T> findByName(String name) { List<T> results = entityManager. createQuery(<font>"select u from User u where u.name=:name"</font><font>) .setParameter(</font><font>"name"</font><font>, name) .getResultList(); <b>return</b> results; } @Override <b>public</b> List<T> findByNameViaSession(String name) { Session session = entityManager.unwrap(Session.<b>class</b>); List<T> results = session.createQuery(</font><font>"select u from User u where u.name=:name"</font><font>) .setParameter(</font><font>"name"</font><font>, name) .list(); <b>return</b> results; } } </font>