简体   繁体   中英

Connection error in spring,Hibernate with Mongodb

Hi i have tried to connect Spring , Hibernate with Mongodb. While trying that i got error like this i don't know what was the mistake i have done in my code so can anyone knows means please let me know.For your reference i have updated my code and error

HibernateConfig.java

import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration  
@EnableTransactionManagement  
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfig 
{
    @Autowired
    private Environment environment;
@Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setPackagesToScan(new String[] { "io.bpk.app.entity"});
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }


    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.ogm.datastore.provider", environment.getRequiredProperty("hibernate.ogm.datastore.provider"));
        properties.put("hibernate.ogm.datastore.host", environment.getRequiredProperty("hibernate.ogm.datastore.host"));
        properties.put("hibernate.ogm.datastore.port", environment.getRequiredProperty("hibernate.ogm.datastore.port"));
        properties.put("hibernate.ogm.datastore.database", environment.getRequiredProperty("hibernate.ogm.datastore.database"));
        properties.put("hibernate.ogm.datastore.create_database", environment.getRequiredProperty("hibernate.ogm.datastore.create_database"));

    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }

}

UserRepositoryImpel.java

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import io.bpk.app.entity.Users;

@Repository("UsersRepository")
public class UserRepositoryImpl implements UsersRepository {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Users create(Users usr) {
        Session session = this.sessionFactory.openSession();
        session .persist(usr);
        return usr;
    }

    @Override
    public Users findByEmail(String email) {
        Session session = this.sessionFactory.openSession();
        TypedQuery<Users> query = session.createNamedQuery("UsersFindByEmail",Users.class);
        query.setParameter("pemail", email);
        try
        {
            Users usr = query.getSingleResult();
            return usr;
        }
        catch (NoResultException nre)
        {
            return null;
        }
    }

    @Override
    public List<Users> findAll() {
        Session session = this.sessionFactory.openSession();
        TypedQuery<Users> query = session.createNamedQuery("UsersFindAll", Users.class);
        return query.getResultList();
    }

}

Userservices.java

  package io.bpk.app.service;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import io.bpk.app.entity.Users;
    import io.bpk.app.exception.UserAlreadyExist;
    import io.bpk.app.repository.UsersRepository;

    @Service
    public class UsersServiceImpl implements UsersService {

        @Autowired
        private UsersRepository repos;


        @Override
        public Users create(Users usr) {
            Users exist = repos.findByEmail(usr.getEmail());
            if(exist!=null)
                throw new UserAlreadyExist("User already exist");
            return repos.create(usr);
        }

        @Override
        public List<Users> findAll() {
            return repos.findAll();
        }

    }

UserRepository.java

package io.bpk.app.repository;

import java.util.List;

import io.bpk.app.entity.Users;

public interface UsersRepository {

    public Users create(Users usr);

    public Users findByEmail(String email);

    public List<Users> findAll();

}

application.properties

 hibernate.ogm.datastore.provider = mongodb
 hibernate.ogm.datastore.host = localhost
 hibernate.ogm.datastore.port = 27017
 hibernate.ogm.datastore.database = local
 hibernate.ogm.datastore.create_database = false
 hibernate.ogm.mongodb.authentication_database = admin

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.bpk</groupId>
    <artifactId>MongoDB-Test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>MongoDB-Test</name>
    <url>https://learn.egen.io</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.ogm</groupId>
            <artifactId>hibernate-ogm-mongodb</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.10.1</version>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-async</artifactId>
            <version>3.10.1</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa</artifactId>
            <version>2.6.3</version>
        </dependency>


        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.nosql</artifactId>
            <version>2.6.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Facing Error

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'usersServiceImpl': Unsatisfied dependency expressed through field 'repos': Error creating bean with name 'UsersRepository': Unsatisfied dependency expressed through field 'sessionFactory': Error creating bean with name 'sessionFactory' defined in io.bpk.app.HibernateConfig: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.internal.SessionFactoryImpl.<init>(Lorg/hibernate/boot/spi/BootstrapContext;Lorg/hibernate/boot/spi/MetadataImplementor;Lorg/hibernate/boot/spi/SessionFactoryOptions;)V; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in io.bpk.app.HibernateConfig: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.internal.SessionFactoryImpl.<init>(Lorg/hibernate/boot/spi/BootstrapContext;Lorg/hibernate/boot/spi/MetadataImplementor;Lorg/hibernate/boot/spi/SessionFactoryOptions;)V; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UsersRepository': Unsatisfied dependency expressed through field 'sessionFactory': Error creating bean with name 'sessionFactory' defined in io.bpk.app.HibernateConfig: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.internal.SessionFactoryImpl.<init>(Lorg/hibernate/boot/spi/BootstrapContext;Lorg/hibernate/boot/spi/MetadataImplementor;Lorg/hibernate/boot/spi/SessionFactoryOptions;)V; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in io.bpk.app.HibernateConfig: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.internal.SessionFactoryImpl.<init>(Lorg/hibernate/boot/spi/BootstrapContext;Lorg/hibernate/boot/spi/MetadataImplementor;Lorg/hibernate/boot/spi/SessionFactoryOptions;)V

I think there is something wrong with the libraries versions you are using. It's hard to say without more details but, if I have to guess, you are using the wrong Hibernate ORM/OGM version for the Spring version you have in the project.

Keep in mind that Hibernate OGM uses ORM underneath and the version added to the project might not be the one you expect.

UPDATE

Spring 4.3.2.RELEASE is compatible with Hibernate ORM 5.2.1.Final (based on this maven repository page ) Hibernate OGM 5.4.1.Final uses Hibernate ORM 5.3.6.Final The Hibernate OGM page has a compatibility matrix page

You need to adjust your dependencies in the pom.xml accordingly. I think these changes will work with Spring 4.3.2 (I haven't tried them):

  • Spring version: 4.3.2.RELEASE
  • OGM version: 5.3.1.Final
  • Remove Hibernate ORM dependency (OGM and Spring already include it as transitive dependency)
  • Remove mongo-java-driver dependency (it's already a transitive OGM dependency)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM