技术控

    今日:117| 主题:49431
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Spring Data Series: Spring Data in a Nutshell

[复制链接]
凉透还能再暖 发表于 2016-10-6 14:28:24
67 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
In this series, we will deep dive into the Spring Data architecture. In this article, we will concentrate on the features of Spring Data and what it has to offer.
  Why Spring Data?  

  Spring Data is an umbrella that takes care of SQL and NoSQL databases and reduces the effort to use them. The Spring community’s motto is to reduce boilerplate code, so the community invented    Spring Data, which is taken one step forward than the database template. In a JPA template, although Spring hides the creation EntityManagerFactory managing Entity manager but the problem is we still have to maintain a DAO layer and provide CRUD operations for each entity. CRUD operations are similar in nature you have framed it in your mind but still, have to write or copy and paste same code over and over for different Entities.  
  Spring address this problem and introduce Spring data which says you don’t have to write redundant code for CRUD just define an interface, Spring creates the actual implementation on the fly. Pure magic.
  Spring Data Repository  

  Spring Data introduced the Repository concept. Repository acts like Adapter. It takes the Entity and makes the persistence layer a specific call — it may be JPA or MongoDB, etc. The beauty of Repository is we just need to create the Interface, which will extend Spring Data’s    Repositorymarker interface. By doing so, you instruct Spring to find those interfaces, which will extend the Repository interface and add them as a Spring bean by creating a Proxy and delegate the call to actual implementation. But as developers, we don’t have to write the actual implementation — we just need to mention what methods we need Spring to take care of that by the     Create and Derivationapproach.  
  Choosing the Underlying Persistence Layer  

  As I said earlier, Spring Data is like an umbrella. It contains different types of persistence layers like JPA and MongoDB so, as a client, you need to instruct Spring Data which persistence layer you want to use. So Spring Data provides different Annotations for different Repositories. If you want to use JPA, just annotate your main class with    @EnableJpaRepositories. If you prefer MongoDB, then it's     @EnableMongoRepositories. Now Spring Data understands that you need a JPA repository or Mongo repository so it can create JPA or Mongo-specific calls. Actually, behind the scenes, Spring Data has an implementation of each Repository like    SimpleJpaRepositoryor    SimpleMongoRepository. Spring Data internally delegates the call to the actual implementation.  
  Different Repositories  

  Spring Data provides various Repository interfaces, which extend the Marker interface Repository. You can choose them based on your need. Just create a custom interface and extend one of the Repository interfaces.
  Two important Repository interfaces are:
  
       
  •       CRUDRepository
       
  •       PagingAndSortingRepository
      
  CRUDRepository  

  Use when you need to perform CRUD operation (Create,Read,Update,Delete)  
  1. public interface CrudRepository<T, ID extends Serializable>
  2.     extends Repository<T, ID> {                                                                                                                        
  3.     <S extends T> S save(S entity);                                                                                                                        
  4.     T findOne(ID primaryKey);                                                                                                                        
  5.     Iterable<T> findAll();
  6.     Long count();                                                                                                                        
  7.     void delete(T entity);                                                                                                                        
  8.     boolean exists(ID primaryKey);
  9. }    // … more functionality omitted.
复制代码
PagingAndSortingRepository  

  Use when you want to use paging and sorting.
  1. public interface PagingAndSortingRepository<T, ID extends Serializable>
  2.     extends CrudRepository<T, ID> {
  3.     Iterable<T> findAll(Sort sort);
  4.     Page<T> findAll(Pageable pageable);
  5. }
复制代码
Assumption  

  
       
  • We use JPA for the Repository.   
  • We use a MySQL database persistence layer.  
  So, to introduce Spring Data in your project, the following steps are needed.
  1. Add Spring Data JPA dependencies into the pom.xml.
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jpa</artifactId>
  4. </dependency>
复制代码
2. Add target database driver. We use MySQL, so we add the following:
  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <scope>runtime</scope>
  5. </dependency
复制代码
3. Create a Person Entity.
  4. Create a Person table in MySQL database.
  5. Create a PersonRepository, which extends CRUDRepository.
  6. Put    @EnableJpaRepositoriesover the main class.  
  Now run the application. Data will successfully save in the database.
      The Code  

  As I use Spring Boot, I use database details in application.properties:
  1. spring.datasource.url=jdbc:mysql://localhost:3306/testdb
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
复制代码
  1. package com.example.cab;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.GenerationType;
  5. import javax.persistence.Id;
  6. @Entity
  7. public class Person {
  8.     @Id
  9.     @GeneratedValue(strategy=GenerationType.AUTO)
  10.     private Long id;
  11.     private String name;
  12.     private String country;
  13.     private String gender;
  14.     public String getName() {
  15.         return name;
  16.     }
  17.     public void setName(String name) {
  18.         this.name = name;
  19.     }
  20.     public String getCountry() {
  21.         return country;
  22.     }
  23.     public void setCountry(String country) {
  24.         this.country = country;
  25.     }
  26.     public String getGender() {
  27.         return gender;
  28.     }
  29.     public void setGender(String gender) {
  30.         this.gender = gender;
  31.     }
  32.     public Long getId() {
  33.         return id;
  34.     }
  35.     public void setId(Long id) {
  36.         this.id = id;
  37.     }
  38.    
  39.     @Override
  40.     public String toString() {
  41.         return "Person [id=" + id + ", name=" + name + ", country=" + country + ", gender=" + gender + "]";
  42.     }
  43. }
  44. package com.example.cab;
  45. import java.util.List;
  46. import org.springframework.data.repository.CrudRepository;
  47. public interface PersonRepositary extends CrudRepository<Person, Long> {
  48.     List<Person> findByCountryContains(String country);
  49. }
  50. package com.example.cab;
  51. import org.slf4j.Logger;
  52. import org.slf4j.LoggerFactory;
  53. import org.springframework.boot.CommandLineRunner;
  54. import org.springframework.boot.SpringApplication;
  55. import org.springframework.boot.autoconfigure.SpringBootApplication;
  56. import org.springframework.context.annotation.Bean;
  57. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  58. @SpringBootApplication
  59. @EnableJpaRepositories
  60. public class PersonApplication {
  61.     private static final Logger log = LoggerFactory.getLogger(PersonApplication.class);
  62.    
  63.     @Bean
  64.     public CommandLineRunner demo(PersonRepositary repository) {
  65.         Person p = new Person();
  66.         p.setName("Samir mitra");
  67.         p.setCountry("America");
  68.         p.setGender("male");
  69.         repository.save(p);
  70.         log.info("Person created" + p);
  71.         return null;
  72.     }
  73.     public static void main(String[] args) {
  74.         SpringApplication.run(PersonApplication.class, args);
  75.     }
  76. }
  77. Output: Person createdPerson [id=4, name=Samir mitra, country=America, gender=male]
复制代码
Adding an Extra Filter Query in Interface  

  Sometimes you want to create a query based on a property that is not in the     CRUDRepositoryinterface. You have to provision to do so. Just declare a method in your custom interface, which must have to obey the syntax. Then, Spring Data creates the query for you on the fly.  
  The syntax is    Queryname<java property><Operation>, like we create a query in the Person Repository —           List<Person> findByCountryContains(String country);      
  If you run the application, the output will be:
  1. Hibernate:
  2.     select
  3.         person0_.id as id1_0_,
  4.         person0_.country as country2_0_,
  5.         person0_.gender as gender3_0_,
  6.         person0_.name as name4_0_
  7.     from
  8.         person person0_
  9.     where
  10.         person0_.country like ?
  11. 2016-09-24 21:37:32.334  INFO 6384 --- [           main] com.example.cab.PersonApplication        : Person Person [id=1, name=Shamik mitra, country=India, gender=male]
  12. 2016-09-24 21:37:32.334  INFO 6384 --- [           main] com.example.cab.PersonApplication        : Person Person [id=2, name=Swastika mitra, country=India, gender=Female]
  13. 2016-09-24 21:37:32.334  INFO 6384 --- [           main] com.example.cab.PersonApplication        : Person Person [id=3, name=Swastika mitra, country=India, gender=Female]
复制代码
Delete Operation  

  When the discussion comes to deletion, a curious mind often asks, "Does Spring Data support soft deletes?" The answer is no. Spring Data only supports physical deletes as of now.
  Use a Handcrafted Query  

  If you want, you can use your handcrafted query with the @Query interface. One use case may be that you don’t want a physical delete, so you override the Spring Data query with your handcrafted soft delete query.  
  Just redefine the method, add @Query, and pass the query.
  1. @Query("select p from Person p where p.country like ?1")
  2. List<Person> findByCountryContains(String country);
复制代码
Query DSL  

  When you search an entity by its properties in Spring Data, you declare them in the interface. But what if you want to create a query that will search the entity dynamically?  
  What Do You Do?  

  One approach is declaring a method in all possible combinations, but this is a bad idea. Your interface will be long and, with additions and deletions, property combinations will need to be modified.
  Criteria API is the solution; we use Criteria API for the same reason. We can introduce a Predicate and query DSL for it.
  Spring Data uses queries, which is quite similar to the Criteria API, but with a different approach. Just like the JPA, Criteria API uses a Java 6 annotation processor to generate meta-model objects, but it produces a much more approachable API.
  To enable it, add the following plugin in pom.xml.
  1. <plugin>
  2.     <groupId>com.mysema.maven</groupId>
  3.     <artifactId>maven-apt-plugin</artifactId>
  4.     <version>1.0</version>
  5.     <executions>
  6.         <execution>
  7.             <phase>generate-sources</phase>
  8.             <goals>
  9.                 <goal>process</goal>
  10.             </goals>
  11.             <configuration>
  12.                 <outputDirectory>target/generated-sources</outputDirectory>
  13.                 <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
  14.             </configuration>
  15.         </execution>
  16.     </executions>
  17. </plugin>
复制代码
In the output directory, it creates a special class —    QPerson. Using    QPerson.person, we can access every property and build our query.  
  Benefits of Spring Data  

  
       
  •       Get rid of boilerplate DAO classes.
       
  •       Easily switch from repository one to another.
       
  •       You don’t have to be an expert in JPA or Mongo queries. Spring will take care of it in an optimized way.
       
  •       Highly flexible and support to add your own custom queries.
      
友荐云推荐




上一篇:iOS开发 路还很长
下一篇:Using a simple SQLite database in your Android app
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表