2017-01-09 2 views
4

SSCCE est ici: https://github.com/dims12/TrySpringJpaPlusHibernateComment trouver la paire de versions compatibles d'Hibernate + Spring-JPA? (Impossible d'ouvrir JPA EntityManager pour la transaction)

Je suis en train de courir sans printemps JPA persistence.xml et ont la configuration suivante:

@Configuration 
@ComponentScan 
@ImportResource("classpath:data_source.xml") 
@EnableJpaRepositories("org.inthemoon.train.chinese.repositories") 
public class BaseConfig { 
    @Autowired 
    private DataSource dataSource; 

    @Bean 
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 
     LocalContainerEntityManagerFactoryBean ans = 
     new LocalContainerEntityManagerFactoryBean(); 
     ans.setDataSource(dataSource); 
     ans.setJpaVendorAdapter(jpaVendorAdapter()); 
     ans.setPackagesToScan("org.inthemoon.train.chinese.data"); 
     return ans; 
    } 

    @Bean 
    public JpaVendorAdapter jpaVendorAdapter() { 
     HibernateJpaVendorAdapter ans = new HibernateJpaVendorAdapter(); 
     ans.setShowSql(false); 
     ans.setGenerateDdl(true); 
     ans.setDatabase(Database.H2); 
     return ans; 
    } 

    @Bean 
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { 
     JpaTransactionManager ans = new JpaTransactionManager(); 
     ans.setEntityManagerFactory(emf); 

     return ans; 
    } 

} 

il cause l'exception suivante

Exception in thread "main" org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NoSuchMethodError: org.hibernate.Session.getFlushMode()Lorg/hibernate/FlushMode; 
... 

PS Est-il possible de configurer IoC dès la première tentative?

MISE À JOUR

J'utilise libs suivants:

compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.5.Final' 

compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '1.10.5.RELEASE' 

MISE À JOUR 2

J'ai essayé 8 différentes versions de hibernate-core pour construire avec ressort JPA de 1.10.5.RELEASE.

versions de 5.2.1-5.2.6 étaient à l'origine de la même exception

NoSuchMethodError: org.hibernate.Session.getFlushMode()Lorg/hibernate/FlushMode; 

Versions 5.1.3 et 5.0.11 provoquaient

ClassNotFoundException: org.hibernate.ejb.HibernateEntityManagerFactory 

Et la seule version était plus complexe causant quelque chose était 5.2.0. Il était à l'origine

SchemaManagementException: Attempt to resolve foreign key metadata from JDBC metadata failed to find column mappings for foreign key named [FKLOK22W31RKBMIIC2J96T9LTCN 

Les questions ont été soulevées:

1) Est-ce que cela signifie que la version à savoir 5.2.0 est compatible avec 1.10.5?

2) Comment le saurais-je sans expérience?

3) Est-ce normal de deviner les versions de cette façon? Le but des outils de gestion de la dépendance n'était-il pas d'éviter de telles choses? Si spring-data-jpa:1.10.5 dépend de l'hibernation de 5.2.0 alors pourquoi cela n'est-il pas décrit dans POM?

MISE À JOUR 3

Sur l'exemple de la boîte: https://github.com/dims12/TrySpringJpaPlusHibernate

Il ne fonctionne pas.

+2

Version incompatible de JPA et Hibernate – shazin

+0

@shazin comment trouver la paire compatible? – Dims

+0

Il semble que hibernate 5.2.x soit supporté par la ligne 1.10.x de spring-data-jpa basée sur le fichier pom pour spring-data-jpa: https://github.com/spring-projects/spring-data- jpa/blob/1.10.x/pom.xml – LucasP

Répondre

5

printemps données JPA v1.10.6 dépend de v4.2 de printemps (v4.2.9 pour être précis) et v4.2 Spring ne supporte pas Hibernate v5.2 . Support pour Hibernate v5.2 a été ajouté only in Spring v4.3. Par conséquent, vous devez mettre à niveau les dépendances Spring vers v4.3.


Ajout des dépendances suivantes dans le fichier construire Gradle devrait fonctionner:

compile 'org.springframework:spring-beans:4.3.4.RELEASE' 
compile 'org.springframework:spring-context:4.3.4.RELEASE' 
compile 'org.springframework:spring-context-support:4.3.4.RELEASE' 
compile 'org.springframework:spring-core:4.3.4.RELEASE' 
compile 'org.springframework:spring-jdbc:4.3.4.RELEASE' 
compile 'org.springframework:spring-orm:4.3.4.RELEASE' 
compile 'org.springframework:spring-tx:4.3.4.RELEASE' 

Votre code modifié available on Github. Exécutez les tests Gradle en tant que gradle test pour vérifier que tout fonctionne correctement.

+0

Oh merci beaucoup! – Dims

0

généralement lorsque vous avez cette exception, cela signifie que vous devriez avait mise en veille prolongée-entitymanager à votre porm. si vous utilisez Maven, vous pouvez le faire en ajoutant ceci à votre pom

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

Je l'utilise aussi pour définir mon dataSource par un haricot que je n'injectez pas avec autowired que vous avez je ne sais pas si cela fonctionne de cette façon.Je préfère faire comme ça

@Bean 
    public DataSource dataSource() { 
     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName("com.mysql.jdbc.Driver"); 
     dataSource.setUrl("jdbc:mysql://localhost:3306/gescable"); 
     dataSource.setUsername("root"); 
     dataSource.setPassword("root"); 
     return dataSource; 
    } 
+0

'Autowired' est juste parce que c'est une configuration séparée, techniquement c'est un bean. – Dims

+0

L'ajout de 'hibernate-entitymanager' n'a pas aidé – Dims

0

Avez-vous besoin d'inclure hibernate du tout? Printemps données JPA comprend tous les éléments de mise en veille prolongée nécessaires pour autant que je le vois, donc je ne sais pas pourquoi vous avez besoin d'ajouter des dépendances de mise en veille prolongée supplémentaires

+0

Sans Hibernate, je n'ai pas de classes' javax.persistence'. – Dims

1

Je viens de tester cette version dans mon projet:

<hibernate.version>5.2.5.Final</hibernate.version> 
<version>1.10.5.RELEASE</version> 

et cela a fonctionné pour moi.

mon fichier de configuration est comme ceci:

@Configuration 
@EnableTransactionManagement 
@EnableJpaRepositories(basePackages = "ge.shemo.repositories") 
@EnableJpaAuditing 
public class PersistenceConfig { 

@Autowired 
private Environment env; 

@Value("${init-db:false}") 
private String initDatabase; 


@Bean 
public PlatformTransactionManager transactionManager() { 
    EntityManagerFactory factory = entityManagerFactory().getObject(); 
    return new JpaTransactionManager(factory); 
} 


@Bean 
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); 

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); 
    vendorAdapter.setGenerateDdl(Boolean.FALSE); 
    vendorAdapter.setShowSql(Boolean.FALSE); 

    factory.setDataSource(dataSource()); 
    factory.setJpaVendorAdapter(vendorAdapter); 
    factory.setPackagesToScan("ge.shemo"); 

    Properties jpaProperties = getHibernateProperties(); 
    factory.setJpaProperties(jpaProperties); 

    factory.afterPropertiesSet(); 
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver()); 
    return factory; 
} 

private Properties getHibernateProperties() { 
    Properties prop = new Properties(); 
    /*prop.put("hibernate.format_sql", "true");*/ 
    /*prop.put("hibernate.hbm2ddl.auto", "update");*/ 
    //prop.put("hibernate.hbm2ddl.auto", "validate"); 
    // prop.put("hibernate.hbm2ddl.import_files","sql/import.sql"); 
    /*prop.put("hibernate.ejb.entitymanager_factory_name", "irakli");*/ 

    //prop.put("hibernate.show_sql", "true"); 
    prop.put("hibernate.dialect", "ge.shemo.config.SQLServerUnicodeDialect"); 
    return prop; 
} 


@Bean 
public HibernateExceptionTranslator hibernateExceptionTranslator() { 
    return new HibernateExceptionTranslator(); 
} 


@Bean 
public DataSource dataSource() { 
    BasicDataSource ds = new BasicDataSource(); 
    ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 

    ds.setUrl("jdbc:sqlserver://LinkToDB:1433;useUnicode=true;characterEncoding=UTF-8;DatabaseName=Your_DB"); 
    ds.setUsername("USER"); 
    ds.setPassword("PASS"); 
    return ds; 
} 




@Bean 
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) { 

    DataSourceInitializer dataSourceInitializer = new  DataSourceInitializer(); 
    dataSourceInitializer.setDataSource(dataSource); 
    ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); 
    //databasePopulator.addScript(new ClassPathResource("db.sql")); 
    dataSourceInitializer.setDatabasePopulator(databasePopulator); 
    dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase)); 
    return dataSourceInitializer; 
} 


@Bean 
public AuditorAware<Long> createAuditorProvider() { 
    return new SecurityAuditor(); 
} 

@Bean 
public AuditingEntityListener createAuditingListener() { 
    return new AuditingEntityListener(); 
} 



} 
+0

Avez-vous essayé d'effectuer une opération avec la base de données? – Dims

+0

J'ai changé la version dans mon projet actuel - où la première étape est l'autorisation - puis la liste des clients, les activités du client .... Il faisait tout correctement - obtenir des données de DB et écrire des mises à jour SQL Server. – Irakli

+0

Je ne vois aucun code de manipulation de base de données dans votre exemple. Voir mon exemple: https://github.com/dims12/TrySpringJpaPlusHibernate – Dims