Connecting Spring application to MySQL ( Spring MVC, Spring Data JPA, Hibernate ) Old School way

huangapple go评论46阅读模式
英文:

Connecting Spring application to MySQL ( Spring MVC, Spring Data JPA, Hibernate ) Old School way

问题

I understand that you're facing an issue with setting up a Spring MVC application connected to MySQL. The error you're encountering seems related to Hibernate configuration. Here's a brief summary of the problem:

  • The error is caused by a org.hibernate.MappingException stating it couldn't get the constructor for org.hibernate.persister.entity.SingleTableEntityPersister.

To troubleshoot this issue, you can consider the following steps:

  1. Ensure your MySQL server is up and running and you can connect to it using the provided URL, username, and password.

  2. Double-check your Hibernate dialect and other properties in your database.properties file to make sure they are correct.

  3. Verify that your entity classes are correctly annotated and mapped to the database tables.

  4. Check your project's dependencies to ensure you have the correct versions of Spring, Hibernate, and MySQL JDBC driver.

  5. Review your configuration class PersistenceJPAConfig to make sure it's correctly configuring the entityManagerFactory, dataSource, and other components.

  6. Look for any typos or syntax errors in your configuration files, especially in the @PropertySource annotation and property names.

By carefully reviewing these aspects, you should be able to identify and resolve the issue. If you have specific questions about any part of your configuration or code, feel free to ask for further assistance.

英文:

Im trying to setup a basic CRUD app from this tutorial https://www.javaguides.net/2018/11/spring-mvc-5-spring-data-jpa-hibernate-jsp-mysql-tutorial.html but
I get the following exception when trying to connect to MySQL from my Spring MVC Application.
I've tried manually setting the Properties object but it throws the same exception. MySQL is running as well.

  • Java 19
  • MySQL 8.0.33
encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.eg.config.PersistenceJPAConfig: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
01:53:01.161 [localhost-startStop-1] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.eg.config.PersistenceJPAConfig: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1744)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1085)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:855)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548)
	at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:400)
	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4757)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5229)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1424)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1414)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:402)
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
	at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1803)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1740)
	... 21 common frames omitted
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
	at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:123)
	at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
	at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:129)
	at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:300)
	at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
	at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
	at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
	... 25 common frames omitted
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
	at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:91)
	at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:116)
	at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:382)
	at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:519)
	at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
	at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
	... 33 common frames omitted
Caused by: java.lang.reflect.InvocationTargetException: null
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
	at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:88)
	... 42 common frames omitted
Caused by: java.lang.NullPointerException: null
	at javassist.util.proxy.SecurityActions.setAccessible(SecurityActions.java:103)
	at javassist.util.proxy.DefineClassHelper.toClass3(DefineClassHelper.java:151)
	at javassist.util.proxy.DefineClassHelper.toClass2(DefineClassHelper.java:134)
	at javassist.util.proxy.DefineClassHelper.toClass(DefineClassHelper.java:95)
	at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:131)
	at javassist.util.proxy.ProxyFactory.createClass3(ProxyFactory.java:530)
	at javassist.util.proxy.ProxyFactory.createClass2(ProxyFactory.java:515)
	at javassist.util.proxy.ProxyFactory.createClass1(ProxyFactory.java:451)
	at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:422)
	at org.hibernate.proxy.pojo.javassist.JavassistProxyFactory.postInstantiate(JavassistProxyFactory.java:75)
	at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:162)
	at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:156)
	at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:58)
	... 47 common frames omitted

This is my config class

@Configuration
@PropertySource("classpath:database.properties")
@EnableTransactionManagement
@ComponentScan({"com.eg"})
@EnableJpaRepositories(basePackages = "com.eg.repository")
public class PersistenceJPAConfig {

    @Autowired
    private Environment env;

    public PersistenceJPAConfig() {
        super();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPackagesToScan(new String[] {
            "com.eg.entity"
        });
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
        entityManagerFactoryBean.setJpaProperties(additionalProperties());
        return entityManagerFactoryBean;
    }

    final Properties additionalProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
        hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
        return hibernateProperties;
    }

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }

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

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

this is my database.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/public?allowPublicKeyRetrieval=true&useSSL=false
jdbc.user=root
jdbc.pass=root
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false

答案1

得分: 1

The issue is with your JDK, because for the libraries in the link that you provided, JDK8 is being used, and JDK8 works with any version that you give it between Spring 5 and Hibernate 5. Starting from JDK11, you cannot use any lower version of Hibernate than 5.4, and in the link that you provided, Hibernate 5.2 is being used.

So you can either update your hibernate to 5.4.1.Final so that it can work with JDK11 or higher ( I know that 5.4 is minimum for JDK11, not sure about JDK19 ) or use the same JDK as it is being used in the article that you provided.

But my honest suggestion is if you want to follow this example, just install JDK8, there is not a single feature that you will need from JDK19 in this code example. Most of the companies that are running Spring 5 and Hibernate 5 did not go further than JDK11, and the compatibility is the main reason.

Check the compatibility matrix on the link below and you will see that none of version 5 of hibernate even mentions JDK19 in their compatibility between JDK and Hibernate.

https://hibernate.org/orm/releases/

英文:

The issue is with your JDK, because for the libraries in the link that you provided, JDK8 is being used, and JDK8 works with any version that you give it between Spring 5 and Hibernate 5. Starting from JDK11, you cannot use any lower version of Hibernate than 5.4, and in the link that you provided, Hibernate 5.2 is being used.

So you can either update your hibernate to 5.4.1.Final so that it can work with JDK11 or higher ( I know that 5.4 is minimum for JDK11, not sure about JDK19 ) or use the same JDK as it is being used in the article that you provided.

But my honest suggestion is if you want to follow this example, just install JDK8, there is not a single feature that you will need from JDK19 in this code example. Most of the companies that are running Spring 5 and Hibernate 5 did not go further than JDK11, and the compatibility is the main reason.

Check the compatibility matrix on the link below and you will see that none of version 5 of hibernate even mentions JDK19 in their compatibility between JDK and Hibernate.

https://hibernate.org/orm/releases/

huangapple
  • 本文由 发表于 2023年5月15日 04:42:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定