【问题标题】:I want to get the result with multiple mysql db using spring我想使用spring获得多个mysql db的结果
【发布时间】:2020-02-14 06:45:17
【问题描述】:

我想得到使用 spring-boot 得到两个不同数据库的结果,但我现在得到了错误实际上我找不到什么问题..

VO.Dve 代码

package com.example.rest.VO;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Entity
@Table(name = "MART")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dve {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String USER_ID;
    private Integer ID;


    public String getID() {
        return ID;
    }
}

VO.LogVo

package com.example.rest.VO;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;

@Entity
@Table(name = "log")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LogVo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String put_date;
    private Integer SCNT;
    private Integer SENT_TOTAL;
    private Integer SCART;
    private Integer ST_TOTAL;
    private Integer Imby_tables_cnt;
    private Integer Alarm;
    private Integer Alert;
    private Integer Watch;
    private Integer TZ;
    private Integer Normal;
    private Integer Rating_sum;


    public Integer getSENT_TOTAL(){
        return SENT_TOTAL;
    }
}

RestDbConfig

package com.example.rest;


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement

@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = {"com.example.rest.rec.repo"}
)



public class RestDbConfig {

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "db1.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    )
    {
        return builder.dataSource(dataSource).packages("com.example.rest.rec.domain").persistenceUnit("resystem").build();
        }

        @Primary
        @Bean(name = "trasactionManager")
        public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory)
        {
        return new JpaTransactionManager(entityManagerFactory);
        }

}

RidDbConfig

package com.example.rest;


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "ridEntityManagerFactory",
        transactionManagerRef = "ridTransactionManager",
        basePackages = {"com.example.rest.rid.repository.repo"}
)

public class RidDbConfig {
    @Bean(name = "ridDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "ridEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean ridEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
             @Qualifier("ridDataSource") DataSource dataSource
    )
    {
        return builder.dataSource(dataSource).packages("com.example.rest.rid.repository.domain").persistenceUnit("rid").build();
    }

    @Bean(name="ridTransactionManager")
    public PlatformTransactionManager ridTransactionManager(
            @Qualifier("ridEntityManagerFactory")EntityManagerFactory ridEntityManagerFactory
            )
    {
        return new JpaTransactionManager(ridEntityManagerFactory);
    }
}

EmpRepository1

package com.example.rest.rid.repository.repo;
import com.example.rest.VO.LogVo;
import com.example.rest.rid.repository.domain.R1pro;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmpRepository1 extends JpaRepository<LogVo, Integer> {

    @Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
    public List<R1pro> findByLimit();
}

R1pro

package com.example.rest.rid.repository.domain;


public interface R1pro {
    String getSENT_TOTAL();
}

EmpRepository2

package com.example.rest.rec.repo;
import com.example.rest.VO.Dve;
import com.example.rest.rec.domain.R2pro;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmpRepository2 extends JpaRepository<Dve, String> {

    @Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
    public List<R2pro> findByLimit1();
}

R2pro

package com.example.rest.rec.domain;


public interface R2pro {
    String getUSER_ID();
}

EmpController1

package com.example.rest.controller;


import com.example.rest.rec.repo.EmpRepository2;
import com.example.rest.rid.repository.domain.R1pro;
import com.example.rest.rec.domain.R2pro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; 
import org.springframework.web.bind.annotation.RestController;
import com.example.rest.rid.repository.repo.EmpRepository1;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/emp")

public class EmpController1 {
    @Autowired
    private EmpRepository1 empRepository1;
    private EmpRepository2 empRepository2;

    @Autowired
public EmpController1(EmpRepository1 empRepository, EmpRepository2 empRepository2) {
    this.empRepository1 = empRepository1;
    this.empRepository2 = empRepository2;
}

    @RequestMapping(value="/ee", method = RequestMethod.GET)
    @ResponseBody
    public String getCategoryList() {
        R1pro r1pro = empRepository1.findByLimit();

        return r1pro.getSENT_TOTAL();
    }



    @Autowired
    @RequestMapping(value = "/ef",method = RequestMethod.GET)
    @ResponseBody
    public String getgiem(){
        R2pro r2pro =empRepository2.findByLimit1();

        return r2pro.getUSER_ID();
    }
}

应用

package com.example.rest;
import com.example.rest.rid.repository.repo.EmpRepository1;
import com.example.rest.rec.repo.EmpRepository2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


}

所以当我运行代码时,我得到了这个错误

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController1' defined in file [C:\Users\DS-18-D3-023\Desktop\data-migration-new-indicator\springboottutorial\target\classes\com\example\rest\controller\EmpController1.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository2': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.Dve

怎么了..请教我

所有的 VO 都是正确的列 当我单独运行代码时效果很好

所有错误

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController1' defined in file [C:\Users\DS-18-D3-023\Desktop\data-migration-new-indicator\springboottutorial\target\classes\com\example\rest\controller\EmpController1.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1276) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1133) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.example.rest.Application.main(Application.java:12) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_231]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_231]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_231]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_231]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.3.RELEASE.jar:2.0.3.RELEASE] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1708) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 24 common frames omitted Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:473) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:73) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:181) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:119) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:102) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:298) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:287) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:63) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:290) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1704) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 35 common frames omitted


Process finished with exit code 0

【问题讨论】:

  • 你能从public String getgiem() 中删除@Autowired 吗?并改为注释private EmpRepository2 empRepository2;
  • 现在我做到了,但我得到了同样的错误
  • '@Autowired' 不适用于 i gotit 类型
  • 糟糕,我刚刚看到您在字段和构造函数上都使用了@Autowired。您可以在字段或构造函数上使用它。 JpaRepository 第二个参数需要是 id 类型。在您的情况下,String 用于两个存储库。
  • 没有 R1pro 有 Integet 所以我需要一个 Integer 和一个 String

标签: java mysql hibernate spring-boot


【解决方案1】:

试试这个

@Repository
public interface EmpRepository1 extends JpaRepository<LogVo, String> {

@Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
public List<R1pro> findByLimit();
}

在 EmpRepository1.java 将 JpaRepository 更改为 JpaRepository 作为 String 类型实体中的 id

【讨论】:

    【解决方案2】:

    好的,您的代码存在一些重大问题:

    1) @Autowired 来自控制器在字段和构造函数上 - 您可以在字段上使用它,也可以在构造函数上使用它(我建议您在构造函数上使用它,因为控制器在没有存储库的情况下无用)并且您需要多了一个参数EmpRepository1 empRepository1

    解决方案:

    private EmpRepository1 empRepository1;
    private EmpRepository2 empRepository2;
    
    @Autowired
    public EmpController1(EmpRepository2 empRepository2, EmpRepository1 empRepository1) {
        this.empRepository1 = empRepository1;
        this.empRepository2 = empRepository2;
    }
    

    2) @Autowired 来自 public String getgiem()(这是不正确的)

    解决方法:去掉注释

    3) 存储库的方法返回类型 R2ProR1Pro 。一旦你扩展了JpaRepository,请注意通用接口是JpaRepository&lt;T,ID&gt;,并且每个方法都需要void,或者T返回类型。

    解决方案:更改方法中预期的返回类型:

    原文:

    @Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
    public List<R2pro> findByLimit1();
    

    修改:

    @Repository
    public interface EmpRepository2 extends JpaRepository<Dve, String> {
    
    @Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
    public List<Dve> findByLimit1(); // List<Dve> return type.
    }
    

    并且@Id注解的字段类型需要在EmpRepository1中相同(String原文:

    @Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
    public List<R1pro> findByLimit();
    

    修改:

    @Repository
    public interface EmpRepository1 extends JpaRepository<LogVo, String> {
    
    @Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
    public List<LogVo> findByLimit();
    }
    

    P.S.:如果您的查询类似于 "SELECT user_id FROM MART limit 1",您可以使用非原始数据类型,例如 IntegerLong 等(仅在您不需要整个对象的情况下)

    例如:

    @Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
    public List<String> findByLimit1(); // the user_id is of String type
    }
    

    一旦您在查询中使用limit 1,这意味着您只需要一个结果,而不是一个列表。所以List&lt;&gt; 不是必需的。

    【讨论】:

    • 我不明白更改您的方法中预期的返回类型:
    • 我该怎么做?/
    • 我已经为问题提供了解决方案。您需要使用我的答案中的代码更改您的原始代码。
    猜你喜欢
    • 2016-06-04
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多