What Is Spring Data JPA PDF
What Is Spring Data JPA PDF
3. Generated queries
www.thoughts-on-java.org
What is Spring Data JPA?
Another comfortable feature of Spring Data JPA is the generation of
database queries based on method names. As long as your query isn’t
too complex, you just need to define a method on your repository
interface with a name that starts with find…By. Spring then parses
the method name and creates a query for it.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
In the next step, you can configure your database connection in the
application.properties or application.yml file. If you use JPA outside
of Spring, you need to configure this and a few other things in the
persistence.xml. Spring Boot and Spring Data JPA handle the default
configuration for you, so that you only need to override the
parameters you want to change.
spring.datasource.url = jdbc:postgresql://localhost:5432/recipes
spring.datasource.username = postgres
spring.datasource.password = postgres
www.thoughts-on-java.org
What is Spring Data JPA?
Repositories in Spring Data JPA
After setting everything up, it’s time to take a closer look at
repositories. There are 3 repository interfaces that you should know
when you use Spring Data JPA:
CrudRepository
PagingAndSortingRepository
JpaRepository
As you might guess from its name, the CrudRepository interface
defines a repository that offers standard create, read, update and
delete operations. The PagingAndSortingRepository extends the
CrudRepository and adds findAll methods that enable you to sort the
result and to retrieve it in a paginated way. Both interface are also
supported by other Spring Data projects, so that you can apply the
same concepts to different datastores. The JpaRepository adds JPA-
specific methods, like flush() to trigger a flush on the persistence
context or findAll(Example<S> example) to find entities by example,
to the PagingAndSortingRepository.
www.thoughts-on-java.org
What is Spring Data JPA?
Working with Repositories
After you defined your repository interface, you can use the
@Autowired annotation to inject it into your service implementation.
Spring Data will then provide you with a proxy implementation of
your repository interface. This proxy provides default
implementations for all methods defined in the interface.
In your business code, you can then use the injected repository to
read entities from the database and to persist new or changed
entities.
@RunWith(SpringRunner.class)
@SpringBootTest
public class GettingStartedApplicationTests {
@Autowired
private BookRepository bookRepository;
@Test
@Transactional
public void testByTitle() {
Book b = bookRepository.findByTitle("Hibernate Tips");
Assert.assertEquals(new Long(1), b.getId());
}
}
www.thoughts-on-java.org