Spring中的连接错误,使用Mongodb休眠

Posted

技术标签:

【中文标题】Spring中的连接错误,使用Mongodb休眠【英文标题】:Connection error in spring,Hibernate with Mongodb 【发布时间】:2019-07-25 18:23:28 【问题描述】:

我尝试将 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

【问题讨论】:

显示你的UsersRepository界面 你能在类中添加包吗? 我已经在代码中添加了所有包 @AndrewNepogoda 我添加了接口代码 UserRepository.java @Hariprasath 你有UsersRepository的实现吗? 【参考方案1】:

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

请记住,Hibernate OGM 在底层使用 ORM,添加到项目中的版本可能不是您所期望的。

Spring 4.3.2.RELEASE 与 Hibernate ORM 5.2.1.Final 兼容(基于this maven repository page) Hibernate OGM 5.4.1.Final 使用 Hibernate ORM 5.3.6.Final Hibernate OGM 页面有一个compatibility matrix page

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

春季版:4.3.2.RELEASE OGM 版本:5.3.1.Final 删除 Hibernate ORM 依赖项(OGM 和 Spring 已将其作为传递依赖项包含) 移除 mongo-java-driver 依赖(它已经是传递 OGM 依赖)

【讨论】:

但我在 Hibernate ORM/OGM 上添加了最新版本 它们都是不同的项目。这意味着它们中的每一个的最新版本都不会自动兼容,除非有某种明确的协议(没有)。您需要检查每个项目需要哪些依赖项并相应地添加正确的版本。我已经用一组应该可以工作的版本更新了我的答案(我还没有尝试过)。 我改变了依赖关系。但是它抛出了不同的错误 面临错误:创建 io.bpk.app.HibernateConfig 中定义的名称为“sessionFactory”的 bean 时出错:调用 init 方法失败;嵌套异常是 org.hibernate.service.spi.ServiceException:无法创建请求的服务 [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] 您需要将持久化提供程序设置为 org.hibernate.ogm.jpa.HibernateOgmPersistence。通常你在persistence.xml中做,这里以persistence.xml为例:github.com/hibernate/hibernate-ogm/blob/master/core/src/test/…

以上是关于Spring中的连接错误,使用Mongodb休眠的主要内容,如果未能解决你的问题,请参考以下文章

Docker,Mongodb,Windows 上的 Spring Boot 出现连接被拒绝错误

尝试将 Spring Boot 应用程序与 mongoDB 连接时出错

Spring Boot MongoDB 连接问题

Docker中的Spring Boot未连接到Docker中的Mongo

Pycharm连接mongodb出现10061错误解决办法

无法在 Docker-Compose 中使用 Spring Boot 连接到 MongoDB