Spring Dtata JPA - 图文

更新时间:2023-10-19 07:15:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

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 { }

//如上面代码: jpaTests 是我自己创建的一个接口,该接口继承了

JpaRepository 该接口引用泛型,T指该接口实现的实体类,ID是主键的类型。不用编写任何代码即可使用jpa带来的敏捷开发,对我们开发人员来说无疑是欣喜若狂。

那这个接口都实现了哪些方法呢?你可以去Spring Data Jpa的源码中看,该接口有个实现里面就是它方法的实现逻辑算法: 下面我贴出代码:

@Transactional(readOnly = true) public class SimpleJpaRepository implements JpaRepository,

JpaSpecificationExecutor {

private 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 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 = entityManager; this.provider =

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, EntityManager em) {

this(JpaEntityInformationSupport.getMetadata(domainClass, em), em); }

/**

* Configures a custom {@link LockMetadataProvider} to be used to detect {@link LockModeType}s to be applied to * queries. *

* @param lockMetadataProvider */

public void setLockMetadataProvider(LockMetadataProvider lockMetadataProvider) {

this.lockMetadataProvider = lockMetadataProvider; }

private Class getDomainClass() {

return entityInformation.getJavaType(); }

private String getDeleteAllQueryString() {

return getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName()); }

private String getCountQueryString() {

String countQuery = String.format(COUNT_QUERY_STRING, provider.getCountQueryPlaceholder(), \); return getQueryString(countQuery, entityInformation.getEntityName()); }

/*

* (non-Javadoc) * @see

org.springframework.data.repository.CrudRepository#delete(java.io.Serializable) */

@Transactional

public void delete(ID id) {

Assert.notNull(id, \);

if (!exists(id)) { throw new

EmptyResultDataAccessException(String.format(\exists!\,

entityInformation.getJavaType(), id), 1); }

delete(findOne(id)); }

/*

* (non-Javadoc) * @see

org.springframework.data.repository.CrudRepository#delete(java.lang.Object) */

@Transactional

public void delete(T entity) {

Assert.notNull(entity, \);

em.remove(em.contains(entity) ? entity : em.merge(entity)); }

/*

* (non-Javadoc) * @see

org.springframework.data.repository.CrudRepository#delete(java.lang.Iterable) */

@Transactional

public void delete(Iterable entities) {

Assert.notNull(entities, \null!\);

for (T entity : entities) { delete(entity); } }

/*

* (non-Javadoc) * @see

org.springframework.data.jpa.repository.JpaRepository#deleteInBatch(java.lang.Iterable) */

@Transactional

public void deleteInBatch(Iterable entities) {

Assert.notNull(entities, \null!\);

if (!entities.iterator().hasNext()) { return; }

applyAndBind(getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName()), entities, em) .executeUpdate(); }

/*

* (non-Javadoc) * @see org.springframework.data.repository.Repository#deleteAll() */

@Transactional

public void deleteAll() {

for (T element : findAll()) { delete(element); } }

/*

* (non-Javadoc) * @see

org.springframework.data.jpa.repository.JpaRepository#deleteAllInBatch() */

@Transactional

public void deleteAllInBatch() {

em.createQuery(getDeleteAllQueryString()).executeUpdate(); }

/*

* (non-Javadoc) *

* @see *

org.springframework.data.repository.Repository#readById(java.io.Serializable * ) */

public T findOne(ID id) {

Assert.notNull(id, \); return em.find(getDomainClass(), id); }

/*

* (non-Javadoc) * @see

org.springframework.data.repository.CrudRepository#exists(java.io.Serializable) */

public boolean exists(ID id) {

Assert.notNull(id, \);

if (entityInformation.getIdAttribute() != null) {

String placeholder = provider.getCountQueryPlaceholder(); String entityName = entityInformation.getEntityName(); Iterable idAttributeNames = entityInformation.getIdAttributeNames(); String existsQuery =

QueryUtils.getExistsQueryString(entityName, placeholder, idAttributeNames);

TypedQuery query = em.createQuery(existsQuery, Long.class);

if (entityInformation.hasCompositeId()) {

for (String idAttributeName : idAttributeNames) { query.setParameter(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#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 query, CriteriaBuilder cb) { Path path =

root.get(entityInformation.getIdAttribute());

return path.in(cb.parameter(Iterable.class, \)); }

}, (Sort) null).setParameter(\, ids).getResultList(); }

/*

* (non-Javadoc) * @see

org.springframework.data.jpa.repository.JpaRepository#findAll(org.springframework.data.domain.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 PageImpl(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 (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) * @see

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 ? new 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 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.JpaSpecificationExecutor#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) */

@Transactional

public S save(S entity) {

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) */

@Transactional

public T saveAndFlush(T entity) {

T result = save(entity); flush();

return result; }

/*

* (non-Javadoc) * @see

org.springframework.data.jpa.repository.JpaRepository#save(java.lang.Iterable) */

@Transactional

public List save(Iterable entities) {

List result = new ArrayList();

if (entities == null) { return result;

本文来源:https://www.bwwdw.com/article/yhof.html

Top