当前位置: 代码迷 >> java >> Spring连接错误,Mongodb休眠
  详细解决方案

Spring连接错误,Mongodb休眠

热度:100   发布时间:2023-07-26 13:56:11.0

嗨,我尝试将Spring,Hibernate与Mongodb连接。 在尝试我遇到这样的错误时,我不知道我在代码中所做的错误是什么,所以任何人都知道意味着请让我知道。作为参考,我已更新了我的代码和错误

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>

面对错误

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

我认为您使用的库版本有问题。 没有更多细节很难说,但是,如果我不得不猜测,您正在为项目中使用的Spring版本使用错误的Hibernate ORM / OGM版本。

请记住,Hibernate OGM在下面使用ORM,并且添加到项目中的版本可能不是您期望的版本。

UPDATE

Spring 4.3.2.RELEASE与Hibernate ORM 5.2.1.Final兼容(基于 )Hibernate OGM 5.4.1.Final使用Hibernate ORM 5.3.6.Final Hibernate OGM页面具有

您需要相应地在pom.xml中调整依赖项。 我认为这些更改将在Spring 4.3.2中起作用(我还没有尝试过):

  • 春季版本:4.3.2。发布
  • OGM版本:5.3.1.Final
  • 删除Hibernate ORM依赖性(OGM和Spring已经将其包括为传递性依赖性)
  • 删除mongo-java-driver依赖关系(它已经是可传递的OGM依赖关系)
  相关解决方案