JPA使用Spring注释配置应用程序

时间:2015-03-18 12:05:38

标签: spring hibernate jpa

我正在使用spring将纯Hibernate注释配置的应用程序转换为纯Jpa(从sessionFactory到entityManager)。所以下面是一个示例代码:

    @Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class DBConfiguration implements TransactionManagementConfigurer
{

  @Resource
  Environment mEnvironment;

  @Bean
  public DataSource dataSource() 
  {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDriverClassName(mEnvironment.getRequiredProperty("db.driver"));
    dataSource.setJdbcUrl(mEnvironment.getRequiredProperty("db.url"));
    dataSource.setUsername(mEnvironment.getRequiredProperty("db.username"));
    dataSource.setPassword(mEnvironment.getRequiredProperty("db.password"));
    return dataSource;
  }

  public Properties hibernateProperties()
  {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", mEnvironment.getProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", mEnvironment.getProperty("hibernate.show_sql"));
    return properties;
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean sessionFactory() throws IOException
  {    
    JpaVendorAdapter vendor = new HibernateJpaVendorAdapter();
    LocalContainerEntityManagerFactoryBean sessionFactory = new LocalContainerEntityManagerFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setJpaVendorAdapter(vendor);
    sessionFactory.setPackagesToScan("com.utilisoft.urlshortener");
    sessionFactory.setJpaProperties(hibernateProperties());
    sessionFactory.afterPropertiesSet();
    return sessionFactory;
  }

  @Bean
  public JpaTransactionManager transactionManager()
  {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    try
    {
      transactionManager.setEntityManagerFactory(sessionFactory().getObject());
    } catch (IOException e)
    {
      e.printStackTrace();
    }
    return transactionManager;
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
    return new PersistenceExceptionTranslationPostProcessor();
  }  


  @Override
  public PlatformTransactionManager annotationDrivenTransactionManager()
  {
    return transactionManager();
  }

}

然后在我的DAO中我只是(仅用于测试目的):

@Repository("bean")
public class UrlDaoImpl implements UrlDao
{

  @PersistenceContext
  EntityManager entityFactory;

  @Override
  public Shortener getShortener(long aPk)
  {
    return (Shortener) entityFactory.find(Shortener.class, aPk);
  }
}

然后我只是试图通过在另一个类中进行测试来测试它是否有效:

  public static void main(String[] args)
  {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.registerShutdownHook();
    //The class containing all my config
    context.register(DBConfiguration.class);
    context.refresh();
    UrlServiceImpl bean = (UrlServiceImpl)context.getBean("bean");
    long aa = 1;
    Shortener url = (Shortener) bean.getShortener(aa);
    System.out.println(url.getToken());
    context.close();
  }

我得到的错误是:

11:59:20,779  INFO AnnotationConfigWebApplicationContext:510 - Refreshing Root WebApplicationContext: startup date [Wed Mar 18 11:59:20 GMT 2015]; root of context hierarchy
11:59:20,864  INFO AnnotationConfigWebApplicationContext:208 - Registering annotated classes: [class com.utilisoft.urlshortener.config.DBConfiguration]
11:59:21,029  INFO PostProcessorRegistrationDelegate$BeanPostProcessorChecker:309 - Bean 'DBConfiguration' of type [class com.utilisoft.urlshortener.config.DBConfiguration$$EnhancerBySpringCGLIB$$3671bce8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Exception in thread "main" java.lang.NoClassDefFoundError: org.springframework.beans.FatalBeanException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at com.utilisoft.urlshortener.Main.main(Main.java:17)
11:59:21,549  INFO AnnotationConfigWebApplicationContext:862 - Closing Root WebApplicationContext: startup date [Wed Mar 18 11:59:20 GMT 2015]; root of context hierarchy
11:59:21,550  WARN AnnotationConfigWebApplicationContext:880 - Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Wed Mar 18 11:59:20 GMT 2015]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:357)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:804)

更新

我添加了

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>3.2.2.RELEASE</version>
</dependency>

现在它告诉我:

     2:16:33,266  INFO AnnotationConfigWebApplicationContext:510 - Refreshing Root WebApplicationContext: startup date [Wed Mar 18 12:16:33 GMT 2015]; root of context hierarchy
Exception in thread "main" java.lang.NoSuchMethodError: org.springframework.beans.factory.support.DefaultListableBeanFactory.getDependencyComparator()Ljava/util/Comparator;
    at org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors(AnnotationConfigUtils.java:136)
    at org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors(AnnotationConfigUtils.java:120)
    at org.springframework.context.annotation.AnnotatedBeanDefinitionReader.<init>(AnnotatedBeanDefinitionReader.java:83)
    at org.springframework.context.annotation.AnnotatedBeanDefinitionReader.<init>(AnnotatedBeanDefinitionReader.java:66)
    at org.springframework.web.context.support.AnnotationConfigWebApplicationContext.loadBeanDefinitions(AnnotationConfigWebApplicationContext.java:188)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
    at com.utilisoft.urlshortener.Main.main(Main.java:17)

更新:  我的pom.xml文件如下:

    <properties>
        <spring.version>4.1.5.RELEASE</spring.version>
        <hibernate.version>4.3.8.Final</hibernate.version>
        <sql.server.conector.version>4.0</sql.server.conector.version>
        <freemarker.version>2.3.21</freemarker.version>
    </properties>

     <dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.1.5.RELEASE</version>
    </dependency>

    <!-- Hibernate -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <!-- DBConnectionPool -->
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>2.3.2</version>
    </dependency>

    <!-- DBCP -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.0.1</version>
    </dependency>


    <!--SQL Server Connector -->
    <dependency>
        <groupId>com.microsoft.sqlserver.jdbc</groupId>
        <artifactId>sqljdbc4</artifactId>
        <version>${sql.server.conector.version}</version>
    </dependency>


    <!-- Servlet Api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- Commons Lang-3 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
    </dependency>

    <!-- slf4j-log4j -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.6.1</version>
    </dependency>
</dependencies>

我得到的新消息是:

      12:43:37,492  INFO AnnotationConfigWebApplicationContext:510 - Refreshing Root WebApplicationContext: startup date [Wed Mar 18 12:43:37 GMT 2015]; root of context hierarchy
12:43:37,591  INFO AnnotationConfigWebApplicationContext:208 - Registering annotated classes: [class com.utilisoft.urlshortener.config.DBConfiguration]
12:43:37,754  INFO PostProcessorRegistrationDelegate$BeanPostProcessorChecker:309 - Bean 'DBConfiguration' of type [class com.utilisoft.urlshortener.config.DBConfiguration$$EnhancerBySpringCGLIB$$ad11f992] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Exception in thread "main" java.lang.NoClassDefFoundError: org.springframework.beans.FatalBeanException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at com.utilisoft.urlshortener.Main.main(Main.java:17)

1 个答案:

答案 0 :(得分:1)

您似乎错过了类路径中的spring-beans-4.1.5.RELEASE.jar。下载并添加它。这个jar包含缺少的类org.springframework.beans.FatalBeanException