DEV Community

eidher
eidher

Posted on • Updated on

JPA with Spring Boot

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

@Entity
@Table(name="T_ACCOUNT")
public class Account {

    @Id
    @Column(name="ID")
    private Long entityId;

    @Column(name="CREDIT_CARD")
    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 a.email 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;
    }

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

    @Transactional
    public void saveAccount(Account account) {
        accountRepository.save(account);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
tleipzig profile image
Thomas

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

Collapse
 
eidher profile image
eidher

It looks nice. Thank you.