Web Article - Spring 3 and JPA with Hibernate

This article shows how to set up Spring with JPA, using Hibernate as a persistence provider.

The JPA Spring Configuration with Java

@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig{
 
   @Bean
   public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
      LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      em.setDataSource(dataSource());
      em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
 
      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
      em.setJpaVendorAdapter(vendorAdapter);
      em.setJpaProperties(additionalProperties());
 
      return em;
   }
 
   @Bean
   public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
      dataSource.setUrl("jdbc:mysql://localhost:3306/spring_jpa");
      dataSource.setUsername( "tutorialuser" );
      dataSource.setPassword( "tutorialmy5ql" );
      return dataSource;
   }
 
   @Bean
   public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(emf);
 
      return transactionManager;
   }
 
   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
      return new PersistenceExceptionTranslationPostProcessor();
   }
 
   Properties additionalProperties() {
      return new Properties() {
         {  // Hibernate Specific: 
            setProperty("hibernate.hbm2ddl.auto", "create-drop");
            setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
         }
      };
   }
}
The JPA Spring Configuration with XML

 
   
      
      
      
         
      
      
         
            create-drop
            org.hibernate.dialect.MySQL5Dialect
         
      
   
 
   
      
      
      
      
   
 
   
      
   
   
 
   
 

This Spring JPA Tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
Source and full article in Baeldung.com


0 Respostas em "Web Article - Spring 3 and JPA with Hibernate"

Powered by Blogger