简体   繁体   English

无法使用Spring Boot JPA构建Hibernate SessionFactory

[英]Unable to build Hibernate SessionFactory using spring boot jpa

At first I have a model named person. 首先,我有一个名为person的模型。 It worked well and create a table in my database. 它运行良好,并在我的数据库中创建了一个表。 After I add a new model that have a foreign key to it, I have this problem. 添加具有外键的新模型后,我遇到了这个问题。 I don't have a dbconfig.java . 我没有dbconfig.java I just have a application.properties . 我只有一个application.properties like this. 像这样。

spring.thymeleaf.mode=LEGACYHTML5


# Database
spring.datasource.url=jdbc:mysql://localhost:3306/db_example?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# Hibernate
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect

spring.jackson.serialization.indent-output=true

And here are the models 这是模型

person.java person.java

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;

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

@Entity 
@NoArgsConstructor
@AllArgsConstructor
@Data
@NamedQuery(name="Person.withNameAndcollegeNamedQuery", query = "select p from Person p where p.name=?1 and p.college=?2")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private String college;
    private String title;
}

project,java package com.example.model; project,java包com.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;

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

@Entity 
@NoArgsConstructor
@AllArgsConstructor
@Data
@NamedQuery(name="Record.withNmaeAndAddressNamedQuery", query = "select p from Record p where p.name=?1 and address=?2")
public class Project {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String projectName;
    @OneToOne
    private Person person;
    private String description;
    private Subject subject;
    private String date;
}

And this is the console log: 这是控制台日志:

13:30:30.244 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
13:30:30.247 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
13:30:30.248 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/E:/workspace-sts-3.8.4.RELEASE/demo/target/classes/]

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

2017-08-11 13:30:30.474  INFO 12108 --- [  restartedMain] com.example.DemoApplication              : Starting DemoApplication on MoriatyC with PID 12108 (E:\workspace-sts-3.8.4.RELEASE\demo\target\classes started by cmh in E:\workspace-sts-3.8.4.RELEASE\demo)
2017-08-11 13:30:30.475  INFO 12108 --- [  restartedMain] com.example.DemoApplication              : No active profile set, falling back to default profiles: default
2017-08-11 13:30:30.652  INFO 12108 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2350e3c9: startup date [Fri Aug 11 13:30:30 CST 2017]; root of context hierarchy
2017-08-11 13:30:32.149  INFO 12108 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-11 13:30:32.157  INFO 12108 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-08-11 13:30:32.158  INFO 12108 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-08-11 13:30:32.230  INFO 12108 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-08-11 13:30:32.230  INFO 12108 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1580 ms
2017-08-11 13:30:32.350  INFO 12108 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-11 13:30:32.353  INFO 12108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-11 13:30:32.353  INFO 12108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-11 13:30:32.353  INFO 12108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-11 13:30:32.354  INFO 12108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-11 13:30:32.806  INFO 12108 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-08-11 13:30:32.820  INFO 12108 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-08-11 13:30:32.954  INFO 12108 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-08-11 13:30:32.955  INFO 12108 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-08-11 13:30:32.956  INFO 12108 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-08-11 13:30:32.988  INFO 12108 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-08-11 13:30:33.074  INFO 12108 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-08-11 13:30:33.232  WARN 12108 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2017-08-11 13:30:33.237  INFO 12108 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-08-11 13:30:33.249  INFO 12108 --- [  restartedMain] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-11 13:30:33.257 ERROR 12108 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at com.example.DemoApplication.main(DemoApplication.java:13) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.6.RELEASE.jar:1.5.6.RELEASE]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    ... 21 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: com.example.model.Subject, at table: project, for columns: [org.hibernate.mapping.Column(subject)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:398) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.Property.isValid(Property.java:225) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:595) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:265) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 27 common frames omitted

Where is the problem? 问题出在哪儿?

First of all you have to create a Subject entity and map it to your Projects entity with @OneToOne 首先,您必须创建一个Subject实体,并使用@OneToOne将其映射到您的Projects实体。

Add

@OneToOne
    private Subject subject;

in your Project.java file. 在您的Project.java文件中。

Subject.java Subject.java

package com.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Subject {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    //Other fields according to your need and setter/getter

}

After creating the Subject entity you get an error in your Project entity at @NamedQuery line so you have to change your named query like below (you can change fields according to your need) 创建Subject实体后,您在@NamedQuery行的Project实体中会收到一个错误,因此您必须像下面那样更改命名查询(可以根据需要更改字段)

@NamedQuery(name="Project.withProjectNameAndDescriptionQuery", query = "select p from Project p where p.projectName=?1 and p.description=?2")

then problem is Caused by: org.hibernate.MappingException: Could not determine type for: com.example.model.Subject, at table: project, for columns: [org.hibernate.mapping.Column(subject)] . 那么问题是Caused by: org.hibernate.MappingException: Could not determine type for: com.example.model.Subject, at table: project, for columns: [org.hibernate.mapping.Column(subject)] you are using private Subject subject; 您正在使用private Subject subject; into Project entity, and the column name Subject is not determining. Project实体,列名称Subject不确定。 so if Subject entity is present into your entity package the you need to @JoinColumn(name = "SUBJECT_ID") or you can also use another column for mapping. 因此,如果Subject实体存在于您的实体包中,则需要@JoinColumn(name = "SUBJECT_ID")或者您也可以使用另一列进行映射。

@ManyToOne
@JoinColumn(name = "CITY_ID")
private Subject subject;

You have a mapping exception. 您有一个映射异常。 You are using a field subject in your Person Entity which is of Subject class. 您正在“ Person实体中使用属于“ Subject类的字段subject

Hibernate cannot map a field with a complex type to a simple column. Hibernate无法将具有复杂类型的字段映射到简单列。 It has to be an entity defined and mapped. 它必须是定义和映射的实体。

So, to solve your problem, define the class Subject as an entity, map it to your probably already existing Subject table in DB, and then specify the relationship between Person and Subject by annotating the field subject with the appropriate annotation ( @ManyToOne or @OneToOne ) and any @JoinColumn necessary. 因此,要解决你的问题,定义类Subject作为一个实体,它映射到数据库您可能已经存在的主题表,然后指定的关系PersonSubject通过注释字段subject与相应的注释( @ManyToOne@OneToOne )和任何必需的@JoinColumn

By the way I would recommend to define your mapping columns explicitly (annotation @Column if Hibernate doesn't generate the schema. That will allow you to change your variable names without need to change database column names 顺便说一句,我建议您明确定义映射列(如果Hibernate不生成架构,则注释@Column 。这将允许您更改变量名而无需更改数据库列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 启动 JPA @查询和映射问题“无法构建 Hibernate SessionFactory” - Spring Boot JPA @Query and mapping problem“ Unable to build Hibernate SessionFactory” 无法在Spring Boot中构建Hibernate SessionFactory - Unable to build Hibernate SessionFactory in Spring Boot Spring Boot 2:无法构建Hibernate SessionFactory - Spring Boot 2: Unable to build Hibernate SessionFactory PersistenceUnit:默认无法建立Hibernate SessionFactory Spring JPA - PersistenceUnit: default Unable to build Hibernate SessionFactory Spring JPA JPA、Hibernate、postgreSQL:无法构建 Hibernate SessionFactory - JPA, Hibernate, postgreSQL: Unable to build Hibernate SessionFactory JPA Hibernate Persistence 异常 [PersistenceUnit: default] 无法构建 Hibernate SessionFactory - JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory 在Spring Boot中使用Hibernate SessionFactory进行连接泄漏 - Connection leak using Hibernate SessionFactory in Spring Boot 无法初始化 JPA EntityManagerFactory:[PersistenceUnit:默认] 无法构建 Hibernate SessionFactory - Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory Spring Boot - Hibernate SessionFactory 的句柄 - Spring Boot - Handle to Hibernate SessionFactory 使用联接继承时无法构建Hibernate SessionFactory - Unable to build Hibernate SessionFactory when using Joined inheritance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM