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;
...
}
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;
}
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();
}
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;
}
}
Top comments (0)