Java for Web學習筆記(一一三):Spring Data(1)何為Spring Data__Java

來源:互聯網
上載者:User
CRUD並不足夠

在之前學習中,使用了通用倉庫介面GenericRepository,並通過GenericBaseRepository,GenericJpaRepository來具體實現,實現上對於CRUD而言,這類的實現大同小異,此外,我們還需要根據UNIQUE KEY或者KEY去進行查詢,而不僅僅使用primary key,還有根據多個條件去進行查詢或者檢索,對返回的結果進行分頁等等。GenericRepository提供的基礎CRUD是不足夠的。

這些介面的實現是比較繁瑣的,我們以分頁為例。如果我們需要擷取能夠分多少頁,就需要擷取總數,代碼如下:

@PersistenceContext private EntityManager entityManager;@Overridepublic Long count(Predicate ... restrictions) {CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();CriteriaQuery<Long> countCriteria = builder.createQuery(Long.class);Root<TestPage> root = countCriteria.from(TestPage.class);TypedQuery<Long> countQuery = this.entityManager.createQuery(countCriteria.select(builder.count(root)).where(restrictions));return countQuery.getSingleResult();}@Overridepublic List<TestPage> page(int page, int numPerPage, Predicate ... restrictions) {CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();CriteriaQuery<TestPage> criteria = builder.createQuery(TestPage.class);Root<TestPage> root = criteria.from(TestPage.class);TypedQuery<TestPage> pagedQuery = this.entityManager.createQuery(criteria.select(root).orderBy(builder.asc(root.get("userName"))).where(restrictions));//【注意】setFristResult:position of the first result, numbered from 0,這個自動分配的id號從1開始不一樣return pagedQuery.setFirstResult((page -1) *numPerPage).setMaxResults(numPerPage).getResultList();}

我們可以將這兩個方法寫成通用的代碼加入到GenericJpaRepository中,但在擷取分頁的資訊時,可能指定某種或者某些排序,也可以需要進行過濾,也就是在例子中的where(restrictions),這使得調用方陷入到JPA的代碼中,如果根據具體情境具體化,可能需要為很多Entity的倉庫添加代碼,無法做到通用。 Spring Data的作用

倉庫的代碼不包含任何的商務邏輯(在Service),也不包含UI(在Controller),是可以通用的樣板代碼。Spring Data它是獨立於Spring framework的一個項目。程式員只需定義介面,Spring Data在runtime時可以動態產生所需的倉庫代碼。


Spring Data支援JPA,JdbcTemplate,NoSQL等,包含所有這些是Spring Data Commons,我們也可以只選擇實現JAP的部分,即Spring Data JPA。 簡單小例子 Pom的引入

<!--  在我們的小實驗中,spring-data-jpa不能使用2的版本,注入出現異常 --><dependency>    <groupId>org.springframework.data</groupId>    <artifactId>spring-data-jpa</artifactId>    <version>1.11.10.RELEASE<version></dependency>

如果我們希望使用spring data jpa 2的版本(例如2.0.5.RELEASE),就需要升級spring framework至5.x,而spring framework 5.x要求javax.servlet是4.0的。 在上下文配置Spring data

只需加上@EnableJpaRepositories

@EnableJpaRepositories("cn.wei.flowingflying.chapter22.site.repositories")/* 如果我們在entityManagerFactory和transactionManager中沒有使用預設的方法名,需要明確指出 * @EnableJpaRepositories( basePackages = "cn.wei.flowingflying.chapter22.site.repositories" *                         entityManagerFactoryRef = "entityManagerFactoryBean", //預設為entityManagerFactory *                         transactionManagerRef = "jpaTransactionManager" ) //預設為transactionManager */@ComponentScan(    basePackages = "cn.wei.flowingflying.chapter22.site",    excludeFilters = @ComponentScan.Filter({Controller.class, ControllerAdvice.class}))public class RootContextConfiguration implements AsyncConfigurer, SchedulingConfigurer{    ... ...    @Bean    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws PropertyVetoException{        Map<String, Object> properties = new Hashtable<>();        properties.put("javax.persistence.schema-generation.database.action","none");        properties.put("hibernate.show_sql", "true");        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();        factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());        factory.setDataSource(this.springJpaDataSource());        factory.setPackagesToScan("cn.wei.flowingflying.chapter22.site.entity");        factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);        factory.setValidationMode(ValidationMode.NONE);        factory.setJpaPropertyMap(properties);        return factory;    }    @Bean    public PlatformTransactionManager transactionManager() throws PropertyVetoException{        return new JpaTransactionManager(this.entityManagerFactory().getObject());    }}
倉庫介面

既然Spring data可以為我們自動產生代碼,那麼如何寫倉庫的介面就成為關鍵。org.springframework.data.repository.Repository<T, ID extends Serializable>是Spring Data中最基礎的介面,沒有任何方法,其他的介面都是繼承它。T就是Entity的類,ID就是主鍵的類型。

/* CrudRepository是Spring Data提供的介面增刪改查的倉庫介面,我們只需繼承即可,它將提供下面的介面 * ➤ count()返回long,就是total number * ➤ delete(T), delete(ID), delete(Iterable<? extends T>), deleteAll() * ➤ exists(ID)查詢ID是否存在,返回boolean * ➤ findAll(),findAll(Iterable<ID>),均返回Iterable<T> * ➤ findOne(ID) * ➤ save(S),其中S是T的繼承,可能執行insert,也可能執行update操作,返回S(如果是insert,我們可以從中擷取自動分配的ID) * ➤ save(Iterable<S>),返回Iterable<S>,同樣S是T的繼承 */public interface AuthorRepository extends CrudRepository<Author,Long>{}

如果我們需要排序或者分頁,就要繼承org.springframework.data.repository.PagingAndSortingRepository<T, ID extendsSerializable>,提供了:

@Servicepublic class DefaultBookManager implements BookManager {@Inject AuthorRepository authorRepository;@Override@Transactionalpublic List<Author> getAuthors() {//return this.toList(authorRepository.getAll()); //以前的代碼return this.toList(authorRepository.findAll());}@Override@Transactionalpublic void saveAuthor(Author author) {/*  以前的代碼if(author.getId() < 1)this.authorRepository.add(author);elsethis.authorRepository.update(author); */this.authorRepository.save(author);}/* 【問題】為何倉庫返回的是一個Iterable<E>,我們要轉換為Collection,如List。         * 在原生的JDBC鎮南關,繁華的是ResultSet,是Iterable,這使得我們可以執行語句,同時繼續從資料庫中讀取資訊。         * 在事務方法中,我們已經commit了事務,關閉了ResultSet,轉換為list這類collection,確保所有的資料在事務結束前已經被讀取。         */private <E> List<E> toList(Iterable<E> i){List<E> list = new ArrayList<>();i.forEach(list::add);return list;}... ...}
findAll(Sort) findAll(Pageable) 使用倉庫介面
@Servicepublic class DefaultBookManager implements BookManager {@Inject AuthorRepository authorRepository;@Override@Transactionalpublic List<Author> getAuthors() {//return this.toList(authorRepository.getAll()); //以前的代碼return this.toList(authorRepository.findAll());}@Override@Transactionalpublic void saveAuthor(Author author) {/*  以前的代碼if(author.getId() < 1)this.authorRepository.add(author);elsethis.authorRepository.update(author); */this.authorRepository.save(author);}/* 【問題】為何倉庫返回的是一個Iterable<E>,我們要轉換為Collection,如List。         * 在原生的JDBC鎮南關,繁華的是ResultSet,是Iterable,這使得我們可以執行語句,同時繼續從資料庫中讀取資訊。         * 在事務方法中,我們已經commit了事務,關閉了ResultSet,轉換為list這類collection,確保所有的資料在事務結束前已經被讀取。         */private <E> List<E> toList(Iterable<E> i){List<E> list = new ArrayList<>();i.forEach(list::add);return list;}... ...}

相關連結: 我的Professional Java for Web Applications相關文章


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.