To use JPA with Spring we need to implement 4 steps:
- Define mapping metadata in entities
- Define an EntityManagerFactory bean
- Define Transaction Manager and DataSource beans
- 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;
...
}
Define repositories as interfaces
public interface AccountRepository extends Repository<Account,Long> {
public Account findByCreditCardNumber(String creditCardNumber);
}
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();
}
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);
}
}
Top comments (2)
Nice article covering the basics :-) Maybe my tool bootify.io could be useful for you, what do you think?
It looks nice. Thank you.