当前位置: 首页 > 知识库问答 >
问题:

Spring BootHibernate配置

史鹏云
2023-03-14

我是spring框架的新手,目前正在尝试使用hibernate和spring boot JPA连接到MySQL数据库。

有人能帮帮我吗?我因为没有提供实体管理器工厂bean而得到一个错误。

我已经创建了一个公共git存储库,其中包含我在此演示项目中的代码:https://bitbucket.org/stanhurks/demo-spring-boot-rest-api

stacktrace如下所示:

/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home/bin/java "-javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=63728:/Applications/IntelliJ IDEA CE.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Users/Stan/IdeaProjects/Finance API/target/classes:/Users/Stan/.m2/repository/org/hibernate/hibernate-core/4.1.4.Final/hibernate-core-4.1.4.Final.jar:/Users/Stan/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar:/Users/Stan/.m2/repository/org/jboss/logging/jboss-logging/3.3.1.Final/jboss-logging-3.3.1.Final.jar:/Users/Stan/.m2/repository/org/jboss/spec/javax/transaction/jboss-transaction-api_1.1_spec/1.0.0.Final/jboss-transaction-api_1.1_spec-1.0.0.Final.jar:/Users/Stan/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar:/Users/Stan/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar:/Users/Stan/.m2/repository/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar:/Users/Stan/.m2/repository/org/hibernate/common/hibernate-commons-annotations/4.0.1.Final/hibernate-commons-annotations-4.0.1.Final.jar:/Users/Stan/.m2/repository/org/hibernate/hibernate-entitymanager/5.2.3.Final/hibernate-entitymanager-5.2.3.Final.jar:/Users/Stan/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar:/Users/Stan/.m2/repository/org/apache/geronimo/specs/geronimo-jta_1.1_spec/1.1.1/geronimo-jta_1.1_spec-1.1.1.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.5.8.RELEASE/spring-boot-starter-web-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-starter/1.5.8.RELEASE/spring-boot-starter-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot/1.5.8.RELEASE/spring-boot-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.5.8.RELEASE/spring-boot-autoconfigure-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.5.8.RELEASE/spring-boot-starter-logging-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar:/Users/Stan/.m2/repository/ch/qos/logback/logback-core/1.1.11/logback-core-1.1.11.jar:/Users/Stan/.m2/repository/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar:/Users/Stan/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.25/log4j-over-slf4j-1.7.25.jar:/Users/Stan/.m2/repository/org/yaml/snakeyaml/1.17/snakeyaml-1.17.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/1.5.8.RELEASE/spring-boot-starter-tomcat-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.23/tomcat-embed-core-8.5.23.jar:/Users/Stan/.m2/repository/org/apache/tomcat/tomcat-annotations-api/8.5.23/tomcat-annotations-api-8.5.23.jar:/Users/Stan/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.5.23/tomcat-embed-el-8.5.23.jar:/Users/Stan/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/8.5.23/tomcat-embed-websocket-8.5.23.jar:/Users/Stan/.m2/repository/org/hibernate/hibernate-validator/5.3.5.Final/hibernate-validator-5.3.5.Final.jar:/Users/Stan/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar:/Users/Stan/.m2/repository/com/fasterxml/classmate/1.3.4/classmate-1.3.4.jar:/Users/Stan/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.8.10/jackson-databind-2.8.10.jar:/Users/Stan/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.8.0/jackson-annotations-2.8.0.jar:/Users/Stan/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.8.10/jackson-core-2.8.10.jar:/Users/Stan/.m2/repository/org/springframework/spring-web/4.3.12.RELEASE/spring-web-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/spring-aop/4.3.12.RELEASE/spring-aop-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/spring-beans/4.3.12.RELEASE/spring-beans-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/spring-context/4.3.12.RELEASE/spring-context-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/spring-webmvc/4.3.12.RELEASE/spring-webmvc-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/spring-expression/4.3.12.RELEASE/spring-expression-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.5.8.RELEASE/spring-boot-starter-data-jpa-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.5.8.RELEASE/spring-boot-starter-aop-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/aspectj/aspectjweaver/1.8.11/aspectjweaver-1.8.11.jar:/Users/Stan/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.5.8.RELEASE/spring-boot-starter-jdbc-1.5.8.RELEASE.jar:/Users/Stan/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.5.23/tomcat-jdbc-8.5.23.jar:/Users/Stan/.m2/repository/org/apache/tomcat/tomcat-juli/8.5.23/tomcat-juli-8.5.23.jar:/Users/Stan/.m2/repository/org/springframework/spring-jdbc/4.3.12.RELEASE/spring-jdbc-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar:/Users/Stan/.m2/repository/org/springframework/data/spring-data-jpa/1.11.8.RELEASE/spring-data-jpa-1.11.8.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/data/spring-data-commons/1.13.8.RELEASE/spring-data-commons-1.13.8.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/spring-orm/4.3.12.RELEASE/spring-orm-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/springframework/spring-tx/4.3.12.RELEASE/spring-tx-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.25/jcl-over-slf4j-1.7.25.jar:/Users/Stan/.m2/repository/org/springframework/spring-aspects/4.3.12.RELEASE/spring-aspects-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/mysql/mysql-connector-java/5.1.44/mysql-connector-java-5.1.44.jar:/Users/Stan/.m2/repository/org/springframework/spring-core/4.3.12.RELEASE/spring-core-4.3.12.RELEASE.jar:/Users/Stan/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar" it.hurks.Application

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

2017-11-12 19:57:00.502  INFO 3838 --- [           main] it.hurks.Application                     : Starting Application on MacBook-Pro-van-Stan.local with PID 3838 (started by Stan in /Users/Stan/IdeaProjects/Finance API)
2017-11-12 19:57:00.505  INFO 3838 --- [           main] it.hurks.Application                     : No active profile set, falling back to default profiles: default
2017-11-12 19:57:00.566  INFO 3838 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@28194a50: startup date [Sun Nov 12 19:57:00 CET 2017]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (file:/Users/Stan/.m2/repository/org/springframework/spring-core/4.3.12.RELEASE/spring-core-4.3.12.RELEASE.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2017-11-12 19:57:01.874  INFO 3838 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-11-12 19:57:01.892  INFO 3838 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-11-12 19:57:01.893  INFO 3838 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-12 19:57:01.971  INFO 3838 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-11-12 19:57:01.972  INFO 3838 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1410 ms
2017-11-12 19:57:02.094  INFO 3838 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-12 19:57:02.099  INFO 3838 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-12 19:57:02.099  INFO 3838 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-12 19:57:02.099  INFO 3838 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-12 19:57:02.099  INFO 3838 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-12 19:57:02.157  WARN 3838 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'paymentController': Unsatisfied dependency expressed through field 'paymentDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'paymentDao': Cannot create inner bean '(inner bean)#48d293ee' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#48d293ee': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2017-11-12 19:57:02.159  INFO 3838 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-11-12 19:57:02.179  INFO 3838 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-12 19:57:02.241 ERROR 3838 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field paymentDao in it.hurks.controller.PaymentController required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.


Process finished with exit code 1

共有3个答案

袁宜民
2023-03-14

这是应用程序。属性文件信息

    spring.mysql.datasource.url=jdbc:mysql://localhost:3306/testDB
    spring.mysql.datasource.username=test
    spring.mysql.datasource.password=test
    spring.mysql.datasource.driver-class-name=com.mysql.jdbc.Driver

这是基于java的配置

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "mysqlEntityManager",
        transactionManagerRef = "mysqlTransactionManager",
        basePackages = "lk.test.dao"
)
@PropertySource("classpath:application.properties")
public class MySqlDBConfig {

    @Autowired
    Environment environment;


    /**
     * These can't be  Primary
     *
     * @return
     */

    @Bean(name = "mysqlDatasource")
    @ConfigurationProperties(prefix = "spring.mysql.datasource")
    public DataSource mySqlDataSource() {
       DriverManagerDataSource dataSource = new DriverManagerDataSource();               
        dataSource.setDriverClassName(environment.getProperty("spring.mysql.datasource.driver-class-name"));
        dataSource.setUrl(environment.getProperty("spring.mysql.datasource.url"));
        dataSource.setUsername(environment.getProperty("spring.mysql.datasource.username"));
        dataSource.setPassword(environment.getProperty("spring.mysql.datasource.password"));
        return dataSource;
    }


    @Bean(name = "mysqlEntityManager")
    public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactoryBean(@Qualifier("mysqlDatasource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setPersistenceUnitName("mysqlPU");
        emf.setJpaProperties(hibernateProperties());
        emf.setPackagesToScan("lk.test.dto.mysql"); 
        emf.setJpaVendorAdapter(getHibernateAdapter());
        return emf;
    }

    @Bean(name = "mysqlTransactionManager")
    public PlatformTransactionManager mySqlTransactionManager(@Qualifier("mysqlEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    private Properties hibernateProperties() {
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        props.setProperty("hibernate.show_sql", "true");
        return props;
    }

    @Bean
    public JpaVendorAdapter getHibernateAdapter() {
        return new HibernateJpaVendorAdapter();
    }
}
田慈
2023-03-14

尝试注释掉@Transactional注释

   //@Transactional
   public interface PaymentDao extends CrudRepository<Payment, Long> {

    }
闾丘才哲
2023-03-14

添加@EnableJPARepository到您的Application

 类似资料:
  • 我正在创建一个电子商务购物平台。 我有以下3个实体类: > 产品库存 订单 订购的产品 @实体@Getter@Setter@noargsconstuctor@allargsconstuctor公共类ProductInventory{ } @Entity@Getter@Setter@NoArgsConstructor@AllArgsConstructor公共类订单{ } @实体@Setter@Get

  • exVim 的配色由三部分组成: 你自己的Vim配色, exVim 插件的语法高亮和插件的配色. 你可以按照以下步骤来定制你的配色: 安装你的配色 exVim 提供了三种方法安装你的自定义配色 方法1. 在 ex-colorscheme 中安装(推荐) 首选的方法是在 ex-colorschemes 中安装自己的配色, 这种方法仅仅需要你把自己的配色文件放到 vimfiles/bundle/ex-

  • 目录: 在配置项目yml文件中: 问题: null 客户端YML: 有没有人知道我怎样才能在这两种情况下只带一个配置文件?

  • 丰富的过滤器插件的存在是 logstash 威力如此强大的重要因素。名为过滤器,其实提供的不单单是过滤的功能。在本章我们就会重点介绍几个插件,它们扩展了进入过滤器的原始数据,进行复杂的逻辑处理,甚至可以无中生有的添加新的 logstash 事件到后续的流程中去!

  • Codec 是 logstash 从 1.3.0 版开始新引入的概念(Codec 来自 Coder/decoder 两个单词的首字母缩写)。 在此之前,logstash 只支持纯文本形式输入,然后以过滤器处理它。但现在,我们可以在输入 期处理不同类型的数据,这全是因为有了 codec 设置。 所以,这里需要纠正之前的一个概念。Logstash 不只是一个input | filter | outpu

  • 在 “Hello World” 示例中,我们已经见到并介绍了 logstash 的运行流程和配置的基础语法。从这章开始,我们就要逐一介绍 logstash 流程中比较常用的一些插件,并在介绍中针对其主要适用的场景,推荐的配置,作一些说明。 限于篇幅,接下来内容中,配置示例不一定能贴完整。请记住一个原则:Logstash 配置一定要有一个 input 和一个 output。在演示过程中,如果没有写明