DEV Community


Posted on • Updated on

JPA with Spring

To use JPA with Spring we need to implement the next 4 steps.

Define mapping metadata in entities

Use the next annotations:

  • Entity: Mandatory. Marks the class as a JPA persistent class
  • Table: Specifies the exact table name to use on the DB (would be the class name if unspecified)
  • Id: Mandatory. Indicates the field to use as the primary key on the database
  • Column: Name of the column on the table (would be the field name if unspecified)
  • OneToMany: Identifies the field on the 'one' side of a one to many relationship
  • JoinColumn: Identifies the column on the 'many' table containing the column to be used when joining. Usually a foreign key.
  • Transient: Not stored in database
public class Account {

    private Long entityId;

    private String number;
Enter fullscreen mode Exit fullscreen mode

Define an EntityManagerFactory bean

    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setGenerateDdl(true); // creating/updating tables (be careful)
        Properties props = new Properties();
        props.setProperty("hibernate.format_sql", "true");
        LocalContainerEntityManagerFactoryBean emfb = 
            new LocalContainerEntityManagerFactoryBean();
        return emfb;
Enter fullscreen mode Exit fullscreen mode

Define Transaction Manager and DataSource beans

    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);

    public DataSource dataSource(){
            (new EmbeddedDatabaseBuilder())
Enter fullscreen mode Exit fullscreen mode

Define Repository/DAO

public class JpaAccountRepository implements AccountRepository {

    private EntityManager entityManager;

    public Account findByNumber(String number) {
        String jpql = "SELECT a FROM Account a where a.number = :number";
        Account account = entityManager.createQuery(jpql, Account.class)
                .setParameter("number", number).getSingleResult();
        return account;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)