DEV Community

eidher
eidher

Posted on • Edited on

2 3

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
@Entity
@Table(name="T_ACCOUNT")
public class Account {

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

    @Transient
    private String number;
    ...
}
Enter fullscreen mode Exit fullscreen mode

Define an EntityManagerFactory bean

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(true);
        adapter.setGenerateDdl(true); // creating/updating tables (be careful)
        adapter.setDatabase(Database.HSQL);
        Properties props = new Properties();
        props.setProperty("hibernate.format_sql", "true");
        LocalContainerEntityManagerFactoryBean emfb = 
            new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource());
        emfb.setPackagesToScan("com");
        emfb.setJpaProperties(props);
        emfb.setJpaVendorAdapter(adapter);
        return emfb;
    }
Enter fullscreen mode Exit fullscreen mode

Define Transaction Manager and DataSource beans

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

    @Bean
    public DataSource dataSource(){
        return
            (new EmbeddedDatabaseBuilder())
            .addScript("classpath:schema.sql")
            .addScript("classpath:data.sql")
            .build();
    }
Enter fullscreen mode Exit fullscreen mode

Define Repository/DAO

@Repository("accountRepository")
public class JpaAccountRepository implements AccountRepository {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay