jpa基本使用
-
Spring-data-jpa的基本介绍:JPA诞生的缘由是为了整合第三方ORM框架,建立一种标准的方式,百度百科说是JDK为了实现ORM的天下归一,目前也是在按照这个方向发展,但是还没能完全实现。在ORM框架中,Hibernate是一支很大的部队,使用很广泛,也很方便,能力也很强,同时Hibernate也是和JPA整合的比较良好,我们可以认为JPA是标准,事实上也是,JPA几乎都是接口,实现都是Hibernate在做,宏观上面看,在JPA的统一之下Hibernate很良好的运行。
-
配置文件结构
-
<context:property-placeholder location="classpath:your-config.properties" ignore-unresolvable="true" />
<context:component-scan base-package="your service package" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<jpa:repositories base-package="your dao package" repository-impl-postfix="Impl" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" />
<tx:advice id="txAdvice" transaction-manager="transactionManager">
tx:attributes
<tx:method name="" />
<tx:method name="get" read-only="true" />
<tx:method name="find" read-only="true" />
<tx:method name="select" read-only="true" />
<tx:method name="delete" propagation="REQUIRED" />
<tx:method name="update" propagation="REQUIRED" />
<tx:method name="add" propagation="REQUIRED" />
<tx:method name="insert" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>aop:config
<aop:pointcut id="allServiceMethod" expression="execution(* your service implements package..(..))" />
<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
</aop:config>
@PersistenceContext
private EntityManager em;
@SuppressWarnings("unchecked")
public Page<Student> search(User user) {
String dataSql = "select t from User t where 1 = 1";
String countSql = "select count(t) from User t where 1 = 1";
if(null != user && !StringUtils.isEmpty(user.getName())) {
dataSql += " and t.name = ?1";
countSql += " and t.name = ?1";
}
Query dataQuery = em.createQuery(dataSql);
Query countQuery = em.createQuery(countSql);
if(null != user && !StringUtils.isEmpty(user.getName())) {
dataQuery.setParameter(1, user.getName());
countQuery.setParameter(1, user.getName());
}long totalSize = (long) countQuery.getSingleResult();
Page<User> page = new Page();
page.setTotalSize(totalSize);
List<User> data = dataQuery.getResultList();
page.setData(data);
return page;
}
}
-
使用JPA的动态接口
-
public interface JpaSpecificationExecutor
{ T findOne(Specification
spec); List
findAll(Specification spec); Page
findAll(Specification spec, Pageable pageable); List
findAll(Specification spec, Sort sort); long count(Specification
spec);
}