Spring Boot the Spring data JPA Introduction


Spring Boot the Spring data JPA Introduction

JPA stands for Java Persistence API (JPA), he is a standard storage API, while Spring data JPA JPA is a kind of realization that allows us to easily access the data. Naming rules written dao layer interface by convention method well, so that without implementation of the interface, for access and operation of the database. At the same time offers a lot of features such as paging, sorting, complex queries in addition to the CRUD and so on.

Spring data JPA can be seen as a secondary package for Hibernate. This article will be in a specific example to explain, how to use Spring data JPA in the Spring Boot.

Add dependent

We want to add Spring data JPA dependent as follows, in order to facilitate testing, we add a h2-memory database:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

Add entity bean

Let's create an entity bean:

@Entity
@Data
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(nullable = false, unique = true)
    private String title;

    @Column(nullable = false)
    private String author;
}

Creating Dao

public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByTitle(String title);

    @Query("SELECT b FROM Book b WHERE LOWER(b.title) = LOWER(:title)")
    Book retrieveByTitle(@Param("title") String title);
}

All Dao need to inherit Interface Repository, Repository is an empty interface:

@Indexed
public interface Repository<T, ID> {

}

If you want to use the default generic some implementations, you can inherit CrudRepository, PagingAndSortingRepository and JpaRepository.

In the above example we have inherited JpaRepository.

In the above example we have created a method to find by Title:

List<Book> findByTitle(String title);

This way we do not need themselves to achieve, Spring Data JPA will help us to achieve. We can use the find ... By, read ... By, query ... By, count ... By, and get ... By the definition of the format of the query, then is back By Entity attributes. And in addition, we can also use the method to splice Or, we cite the following example:

interface PersonRepository extends Repository<Person, Long> {

  List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

  // Enables the distinct flag for the query
  List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
  List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

  // Enabling ignoring case for an individual property
  List<Person> findByLastnameIgnoreCase(String lastname);
  // Enabling ignoring case for all suitable properties
  List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);

  // Enabling static ORDER BY for a query
  List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
  List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
}

Of course, the stitching processing method, we can also customize sql query:

    @Query("SELECT b FROM Book b WHERE LOWER(b.title) = LOWER(:title)")
    Book retrieveByTitle(@Param("title") String title);

Custom query to the Spring data JPA provides more room for imagination.

Spring Data Configuration

To use the Spring Data JPA, we also need to specify the directories to be scanned in the configuration file, use @EnableJpaRepositories annotations to implement:

@Configuration
@EnableJpaRepositories(basePackages = "com.flydean.repository")
public class PersistenceConfig {
}

We also need to specify the attribute data source in the configuration file:

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

test

With all the above, we can test our sources of data:

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {JpaApp.class})
public class BookRepositoryTest {

    @Autowired
    private BookRepository bookRepository;

    @Test
    @Transactional(readOnly=false)
    public void testBookRepository(){
        Book book = new Book();
        book.setTitle(randomAlphabetic(10));
        book.setAuthor(randomAlphabetic(15));

        bookRepository.save(book);

       bookRepository.findByTitle(book.getTitle()).forEach(e -> log.info(e.toString()));
       log.info(bookRepository.retrieveByTitle(book.getTitle()).toString());
    }
}

The examples herein may refer to: https://github.com/ddean2009/learn-springboot2/tree/master/springboot-jpa

Please refer to more tutorials flydean's blog

Published 113 original articles · won praise 117 · views 320 000 +

Guess you like

Origin blog.csdn.net/superfjj/article/details/104490203