DEV Community


JPA with Spring Boot

Java Developer
・1 min read

To use JPA with Spring we need to implement 4 steps:

  1. Define mapping metadata in entities
  2. Define an EntityManagerFactory bean
  3. Define Transaction Manager and DataSource beans
  4. Define Repository/DAO

With Spring Boot, it automatically creates a DataSource, an EntityManagerFactoryBean, and sets up a JpaTransactionManager. So, to use JPA with Spring Boot we just need to implement 2 steps:

Annotate domain classes

public class Account {

    private Long entityId;

    private String creditCardNumber;
Enter fullscreen mode Exit fullscreen mode

Define repositories as interfaces

public interface AccountRepository extends Repository<Account,Long> {

    public Account findByCreditCardNumber(String creditCardNumber);
Enter fullscreen mode Exit fullscreen mode

Spring Data will implement at run-time scans for interfaces extending Repository. Besides, it will implement CRUD methods (extending CrudRepository), paging and sorting (extending PagingAndSortingRepository), among other subinterfaces. See Repository documentation

Using CrudRepository and custom query (JPQL)

public interface AccountRepository extends CrudRepository<Account,Long> {

    public Account findByCreditCardNumber(String creditCardNumber);

    @Query("SELECT a FROM Account WHERE NOT LIKE '%@%'")
    public List<Account> findInvalidEmails();

Enter fullscreen mode Exit fullscreen mode

Using the repository

public class AccountServiceImpl implements AccountService {

    private AccountRepository accountRepository;

    public AccountServiceImpl(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;

    public Account getAccount(String creditCardNumber) {
        return accountRepository.findByCreditCardNumber(creditCardNumber);

    public void saveAccount(Account account) {;
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

tleipzig profile image

Nice article covering the basics :-) Maybe my tool could be useful for you, what do you think?

eidher profile image
eidher Author

It looks nice. Thank you.