Quantcast
Channel: Spring Community Forums - Data
Viewing all articles
Browse latest Browse all 297

Bug in example code in docs for configuring jpa repositories using java configuration

$
0
0
In this documentation, http://static.springsource.org/sprin...ositories.html , specifically 2.1.2 Annotation based configuration there appears to be a bug in the following example code:

Code:

@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
class ApplicationConfig {

  @Bean
  public DataSource dataSource() {

    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    return builder.setType(EmbeddedDatabaseType.HSQL).build();
  }

  @Bean
  public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.acme.domain");
    factory.setDataSource(dataSource());
    factory.afterPropertiesSet();

    return factory.getObject();
  }

  @Bean
  public PlatformTransactionManager transactionManager() {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory());
    return txManager;
  }
}


The issue is this line:

Code:

  txManager.setEntityManagerFactory(entityManagerFactory());
where the txManager is setting the entityManagerFactory to the result of the method call, rather than to the Spring bean created by the annotation. This exactly the same issue as described here which is a general issue regarding factory beans in java based configuration.

The issue you get with the above code is nothing gets inserted to the database on a transactional save, as the transaction manager isn't correctly bound to the entityManagerFactory.

The fix is this (as described in the previous link)

Code:

@Autowired
private EntityManagerFactory entityManagerFactory;

txManager.setEntityManagerFactory(entityManagerFactory);

Note that elsewhere in the documentation the correct approach is described, e.g.

To access the com.mongodb.Mongo object created by the MongoFactoryBean in other @Configuration or your own classes, use a "private @Autowired Mongo mongo;" field.

Viewing all articles
Browse latest Browse all 297

Trending Articles