You are on page 1of 1

Sold to

Spring Data JPA CheatSheet


robin.424242@gmail.com

Using Spring Boot

Dependency Configure Database Configuration

<dependency> 1. Add DB driver to dependencies By default, all @Entity Repository


and are scanned, starting at the

<groupId>org.springframework.boot</groupId> 2. Configure DB in application properties (


. or yaml) location your main @Configuration
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> spring.datasource.url=jdbc:h2:file:./target/mydb @EnableJpaRepositories : Scans and sets up Repositories

spring.datasource.username=sa @EntityScan @Entity


: Scans for domain models and builds ORM
spring.datasource.password=myfancypassword context

Example:

@EnableJpaRepositories("de.codeboje.example.repos")
@EntityScan("de.codeboje.example.model")

Domain Model Repository

Create an interface and extend from Repository


@Entity : defines a JPA model @Entity
@Id : primary key public class User { Example:

@GeneratedValue : generates PK

@Id public interface UserRepository extends PagingAndSortingRepository<User, Long>{


and all other JPA and Hibernate @GeneratedValue }
annotations private Long id;
Special Repositories

private String username;


} CrudRepository : adds basic CRUD methods

PagingAndSortingRepository : adds paging and sorting methods

Query

Defined on Repository methods

By Method Naming Using @Query With JPQL Paging

findBy, findAllBy, followed by fieldnames joined Parameter ref by position: Pass a parameter of type Pageable and return Page
using AND, OR, etc

@Query("select u from User u where lastname = ?1") Page<User> findAllByLastname(String lastname, Pageable page);
findAllByLastname(String lastname); List<User> findAllByLastname(String lastname);

findFirstByCreationDate Named Parameter: Sorting

findAllByCityOrderByZipCode @Query("select u from User u where lastname = :lastname")


Pass a parameter of type Sort
List<User> findAllByLastname(
@Param("lastname") String lastname List<User> findAllByLastname(String lastname, Sort sort);
);

codeboje.de

You might also like