Spring Dtata JPA_第1页
Spring Dtata JPA_第2页
Spring Dtata JPA_第3页
Spring Dtata JPA_第4页
Spring Dtata JPA_第5页
已阅读5页,还剩9页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、 Spring Data JPA最近项目中使用了Spring Data JPA这套基于持久化层的一套查询规范( 即基于ORM和JPA )。今天自己整理一下这套“框架”的使用说明JPA:JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象关系表的映射关系,并将运行期的实体对象持久化到数据库中。 使用Spring Data Jpa要引入相应的jar 文件。使用此规范只要实现几个重要的接口即可,首先看下这几个接口的关系那了解了接口之后该如何使用呢:public interface JPATests extends JpaRepository /如上面代码:

2、 jpaTests 是我自己创建的一个接口,该接口继承了JpaRepository 该接口引用泛型,T指该接口实现的实体类,ID是主键的类型。不用编写任何代码即可使用jpa带来的敏捷开发,对我们开发人员来说无疑是欣喜若狂。那这个接口都实现了哪些方法呢?你可以去Spring Data Jpa的源码中看,该接口有个实现里面就是它方法的实现逻辑算法:下面我贴出代码:Transactional(readOnly = true)public class SimpleJpaRepository implements JpaRepository,JpaSpecificationExecutor privat

3、e final JpaEntityInformation entityInformation;private final EntityManager em;private final PersistenceProvider provider;private LockMetadataProvider lockMetadataProvider;/* * Creates a new link SimpleJpaRepository to manage objects of the given link JpaEntityInformation. * * param entityInformation

4、 must not be literal null. * param entityManager must not be literal null. */public SimpleJpaRepository(JpaEntityInformation entityInformation, EntityManager entityManager) Assert.notNull(entityInformation);Assert.notNull(entityManager);this.entityInformation = entityInformation;this.em = entityMana

5、ger;vider = PersistenceProvider.fromEntityManager(entityManager);/* * Creates a new link SimpleJpaRepository to manage objects of the given domain type. * * param domainClass must not be literal null. * param em must not be literal null. */public SimpleJpaRepository(Class domainClass, Entity

6、Manager em) this(JpaEntityInformationSupport.getMetadata(domainClass, em), em);/* * Configures a custom link LockMetadataProvider to be used to detect link LockModeTypes to be applied to * queries. * * param lockMetadataProvider */public void setLockMetadataProvider(LockMetadataProvider lockMetadata

7、Provider) this.lockMetadataProvider = lockMetadataProvider;private Class getDomainClass() return entityInformation.getJavaType();private String getDeleteAllQueryString() return getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName();private String getCountQueryString() String count

8、Query = String.format(COUNT_QUERY_STRING, provider.getCountQueryPlaceholder(), %s);return getQueryString(countQuery, entityInformation.getEntityName();/* * (non-Javadoc) * see org.springframework.data.repository.CrudRepository#delete(java.io.Serializable) */Transactionalpublic void delete(ID id) Ass

9、ert.notNull(id, The given id must not be null!);if (!exists(id) throw new EmptyResultDataAccessException(String.format(No %s entity with id %s exists!,entityInformation.getJavaType(), id), 1);delete(findOne(id);/* * (non-Javadoc) * see org.springframework.data.repository.CrudRepository#delete(java.l

10、ang.Object) */Transactionalpublic void delete(T entity) Assert.notNull(entity, The entity must not be null!);em.remove(em.contains(entity) ? entity : em.merge(entity);/* * (non-Javadoc) * see org.springframework.data.repository.CrudRepository#delete(java.lang.Iterable) */Transactionalpublic void del

11、ete(Iterable entities) Assert.notNull(entities, The given Iterable of entities not be null!);for (T entity : entities) delete(entity);/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaRepository#deleteInBatch(java.lang.Iterable) */Transactionalpublic void deleteInBatch(Iterable ent

12、ities) Assert.notNull(entities, The given Iterable of entities not be null!);if (!entities.iterator().hasNext() return;applyAndBind(getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName(), entities, em).executeUpdate();/* * (non-Javadoc) * see org.springframework.data.repository.Re

13、pository#deleteAll() */Transactionalpublic void deleteAll() for (T element : findAll() delete(element);/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaRepository#deleteAllInBatch() */Transactionalpublic void deleteAllInBatch() em.createQuery(getDeleteAllQueryString().executeUpdat

14、e();/* * (non-Javadoc) * * see * org.springframework.data.repository.Repository#readById(java.io.Serializable * ) */public T findOne(ID id) Assert.notNull(id, The given id must not be null!);return em.find(getDomainClass(), id);/* * (non-Javadoc) * see org.springframework.data.repository.CrudReposit

15、ory#exists(java.io.Serializable) */public boolean exists(ID id) Assert.notNull(id, The given id must not be null!);if (entityInformation.getIdAttribute() != null) String placeholder = provider.getCountQueryPlaceholder();String entityName = entityInformation.getEntityName();Iterable idAttributeNames

16、= entityInformation.getIdAttributeNames();String existsQuery = QueryUtils.getExistsQueryString(entityName, placeholder, idAttributeNames);TypedQuery query = em.createQuery(existsQuery, Long.class);if (entityInformation.hasCompositeId() for (String idAttributeName : idAttributeNames) query.setParamet

17、er(idAttributeName, entityInformation.getCompositeIdAttributeValue(id, idAttributeName); else query.setParameter(idAttributeNames.iterator().next(), id);return query.getSingleResult() = 1L; else return findOne(id) != null;/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaRepository

18、#findAll() */public List findAll() return getQuery(null, (Sort) null).getResultList();/* * (non-Javadoc) * see org.springframework.data.repository.CrudRepository#findAll(ID) */public List findAll(Iterable ids) return getQuery(new Specification() public Predicate toPredicate(Root root, CriteriaQuery

19、query, CriteriaBuilder cb) Path path = root.get(entityInformation.getIdAttribute();return path.in(cb.parameter(Iterable.class, ids);, (Sort) null).setParameter(ids, ids).getResultList();/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaRepository#findAll(org.springframework.data.do

20、main.Sort) */public List findAll(Sort sort) return getQuery(null, sort).getResultList();/* * (non-Javadoc) * see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Pageable) */public Page findAll(Pageable pageable) if (null = pageable) return new P

21、ageImpl(findAll();return findAll(null, pageable);/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaSpecificationExecutor#findOne(org.springframework.data.jpa.domain.Specification) */public T findOne(Specification spec) try return getQuery(spec, (Sort) null).getSingleResult(); catch

22、 (NoResultException e) return null;/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework.data.jpa.domain.Specification) */public List findAll(Specification spec) return getQuery(spec, (Sort) null).getResultList();/* * (non-Javadoc) * se

23、e org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework.data.jpa.domain.Specification, org.springframework.data.domain.Pageable) */public Page findAll(Specification spec, Pageable pageable) TypedQuery query = getQuery(spec, pageable);return pageable = null ? ne

24、w PageImpl(query.getResultList() : readPage(query, pageable, spec);/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework.data.jpa.domain.Specification, org.springframework.data.domain.Sort) */public List findAll(Specification spec, Sort

25、 sort) return getQuery(spec, sort).getResultList();/* * (non-Javadoc) * see org.springframework.data.repository.CrudRepository#count() */public long count() return em.createQuery(getCountQueryString(), Long.class).getSingleResult();/* * (non-Javadoc) * see org.springframework.data.jpa.repository.Jpa

26、SpecificationExecutor#count(org.springframework.data.jpa.domain.Specification) */public long count(Specification spec) return getCountQuery(spec).getSingleResult();/* * (non-Javadoc) * see org.springframework.data.repository.CrudRepository#save(java.lang.Object) */Transactionalpublic S save(S entity

27、) if (entityInformation.isNew(entity) em.persist(entity);return entity; else return em.merge(entity);/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaRepository#saveAndFlush(java.lang.Object) */Transactionalpublic T saveAndFlush(T entity) T result = save(entity);flush();return res

28、ult;/* * (non-Javadoc) * see org.springframework.data.jpa.repository.JpaRepository#save(java.lang.Iterable) */Transactionalpublic List save(Iterable entities) List result = new ArrayList();if (entities = null) return result;for (S entity : entities) result.add(save(entity);return result;/* * (non-Ja

29、vadoc) * see org.springframework.data.jpa.repository.JpaRepository#flush() */Transactionalpublic void flush() em.flush();/* * Reads the given link TypedQuery into a link Page applying the given link Pageable and * link Specification. * * param query must not be literal null. * param spec can be lite

30、ral null. * param pageable can be literal null. * return */private Page readPage(TypedQuery query, Pageable pageable, Specification spec) query.setFirstResult(pageable.getOffset();query.setMaxResults(pageable.getPageSize();Long total = QueryUtils.executeCountQuery(getCountQuery(spec);List content =

31、total pageable.getOffset() ? query.getResultList() : Collections. emptyList();return new PageImpl(content, pageable, total);/* * Creates a new link TypedQuery from the given link Specification. * * param spec can be literal null. * param pageable can be literal null. * return */private TypedQuery ge

32、tQuery(Specification spec, Pageable pageable) Sort sort = pageable = null ? null : pageable.getSort();return getQuery(spec, sort);/* * Creates a link TypedQuery for the given link Specification and link Sort. * * param spec can be literal null. * param sort can be literal null. * return */private Ty

33、pedQuery getQuery(Specification spec, Sort sort) CriteriaBuilder builder = em.getCriteriaBuilder();CriteriaQuery query = builder.createQuery(getDomainClass();Root root = applySpecificationToCriteria(spec, query);query.select(root);if (sort != null) query.orderBy(toOrders(sort, root, builder);return applyLockMode(em.createQuery(query);/* * Creates a new count query for the given link Specification. * * param spec can be literal null. * return */private TypedQuery getCountQuery(Specification spec) CriteriaBuilde

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论