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

Springboot::Hibernate::无法构建Hibernate SessionFactory

尹善
2023-03-14

我正在使用Hibernate和spring boot。我注意到,如果我从包中包含注释@CreationTimestamp@UpdateTimestamp

org.hibernate.annotations.CreationTimestamp;
org.hibernate.annotations.UpdateTimestamp;

并尝试运行spring启动应用程序。我的应用程序启动失败,出现以下错误。

""2017-10-10 12:45:18 [restartedMain] ERROR 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)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at com.niti.NitiApplication.main(NitiApplication.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 21 common frames omitted
Caused by: org.hibernate.cfg.NotYetImplementedException: Still need to wire in composite in-memory value generation
    at org.hibernate.tuple.entity.EntityMetamodel$CompositeGenerationStrategyPairBuilder.buildPair(EntityMetamodel.java:574)
    at org.hibernate.tuple.entity.EntityMetamodel.buildGenerationStrategyPair(EntityMetamodel.java:421)
    at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:249)
    at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:517)
    at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:348)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
    ... 27 common frames omitted

当我删除这些注释并尝试运行应用程序时。应用程序启动良好。

审计实体。JAVA

package com.niti.dao.entity;

import java.io.Serializable;
import java.util.Calendar;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;


@Embeddable
public class AuditEntity implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public AuditEntity() {
        // TODO Auto-generated constructor stub
    }
    @Column(name="CREATED_BY")
    private String createdBy;

    @Column(name="LAST_UPDATED_BY")
    private String lastUpdatedBy;

    @Column(name="CREATED_DATE", updatable=false, nullable=false)
    @Temporal(TemporalType.TIMESTAMP)
//  @CreationTimestamp /* i comment this line and the line below @updateTimestap application starts up fine. */
    private Calendar createdDate;

    @Column(name="LAST_UPDATED_DATE", nullable=false)
    @Temporal(TemporalType.TIMESTAMP)
//  @UpdateTimestamp /* i comment this line and the line above @CreationTimestap application starts up fine. */
    private Calendar lastUpdatedDate;

    /*@PrePersist
    public void preInsert() {
        if (createdBy == null || createdBy.length() == 0) {
            createdBy = "System";
        }

        if (lastUpdatedBy == null || lastUpdatedBy.length() == 0) {
            lastUpdatedBy = "System";
        }
    }*/
    /**
     * @return the createdBy
     */
    public String getCreatedBy() {
        return createdBy;
    }

    /**
     * @param createdBy the createdBy to set
     */
    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    /**
     * @return the lastUpdatedBy
     */
    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    /**
     * @param lastUpdatedBy the lastUpdatedBy to set
     */
    public void setLastUpdatedBy(String lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

    /**
     * @return the createdDate
     */
    public Calendar getCreatedDate() {
        return createdDate;
    }

    /**
     * @param createdDate the createdDate to set
     */
    public void setCreatedDate(Calendar createdDate) {
        this.createdDate = createdDate;
    }

    /**
     * @return the lastUpdatedDate
     */
    public Calendar getLastUpdatedDate() {
        return lastUpdatedDate;
    }

    /**
     * @param lastUpdatedDate the lastUpdatedDate to set
     */
    public void setLastUpdatedDate(Calendar lastUpdatedDate) {
        this.lastUpdatedDate = lastUpdatedDate;
    }


}

波姆。xml

    <?xml version="1.0" encoding="UTF-8"?>
<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>com.niti</groupId>
    <artifactId>niti</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>niti</name>
    <description>Niti : HR Management System</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>  -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>1.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency> 
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>16.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

我将审计实体嵌入到userentity中。

下面是userEntity的代码。JAVA

package com.niti.dao.entity;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;



@Entity
@Table(name="user")
public class UserEntity implements Serializable {

    public UserEntity() {

    }
    /**
     * generated serial version uid
     */
    private static final long serialVersionUID = 1L;

    @Embedded
    public AuditEntity auditEntity;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="user", fetch=FetchType.LAZY)
    private List<UserExperienceEntity> userExperiences;



    /**
     * @return the auditEntity
     */
    public AuditEntity getAuditEntity() {
        return auditEntity;
    }

    /**
     * @param auditEntity the auditEntity to set
     */
    public void setAuditEntity(AuditEntity auditEntity) {
        this.auditEntity = auditEntity;
    }
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="USER_ID")
    private Integer userId;

    @Column(name="PREFIX")
    private String prefix;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @Column(name="MIDDLE_NAME")
    private String middleName;

    @Column(name="USER_NUMBER")
    private String userNumber;

    @Column(name="EMAIL_ADDRESS")
    private String emailAddress;

    @Column(name="P_CONTACT_NBR")
    private String primaryContactNumber;

    @Column(name="S_CONTACT_NBR")
    private String secondarayContactNumber;

    @Column(name="EMP_CODE")
    private String employeeCode;

    @Column(name="SALARY")
    private Integer salary;

    @Column(name="STATUS")
    private String status;

    @Column(name="START_DATE")
    private Calendar startDate;

    @Column(name="END_DATE")
    private Calendar endDate;


    /**
     * @return the userId
     */
    public Integer getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    /**
     * @return the prefix
     */
    public String getPrefix() {
        return prefix;
    }

    /**
     * @param prefix the prefix to set
     */
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the middleName
     */
    public String getMiddleName() {
        return middleName;
    }

    /**
     * @param middleName the middleName to set
     */
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    /**
     * @return the userNumber
     */
    public String getUserNumber() {
        return userNumber;
    }

    /**
     * @param userNumber the userNumber to set
     */
    public void setUserNumber(String userNumber) {
        this.userNumber = userNumber;
    }

    /**
     * @return the emailAddress
     */
    public String getEmailAddress() {
        return emailAddress;
    }

    /**
     * @param emailAddress the emailAddress to set
     */
    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    /**
     * @return the primaryContactNumber
     */
    public String getPrimaryContactNumber() {
        return primaryContactNumber;
    }

    /**
     * @param primaryContactNumber the primaryContactNumber to set
     */
    public void setPrimaryContactNumber(String primaryContactNumber) {
        this.primaryContactNumber = primaryContactNumber;
    }

    /**
     * @return the secondarayContactNumber
     */
    public String getSecondarayContactNumber() {
        return secondarayContactNumber;
    }

    /**
     * @param secondarayContactNumber the secondarayContactNumber to set
     */
    public void setSecondarayContactNumber(String secondarayContactNumber) {
        this.secondarayContactNumber = secondarayContactNumber;
    }

    /**
     * @return the employeeCode
     */
    public String getEmployeeCode() {
        return employeeCode;
    }

    /**
     * @param employeeCode the employeeCode to set
     */
    public void setEmployeeCode(String employeeCode) {
        this.employeeCode = employeeCode;
    }

    /**
     * @return the salary
     */
    public Integer getSalary() {
        return salary;
    }

    /**
     * @param salary the salary to set
     */
    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    /**
     * @return the status
     */
    public String getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * @return the startDate
     */
    public Calendar getStartDate() {
        return startDate;
    }

    /**
     * @param startDate the startDate to set
     */
    public void setStartDate(Calendar startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public Calendar getEndDate() {
        return endDate;
    }

    /**
     * @param endDate the endDate to set
     */
    public void setEndDate(Calendar endDate) {
        this.endDate = endDate;
    }

    public List<UserExperienceEntity> getUserExperiences() {
        return userExperiences;
    }

    public void setUserExperiences(List<UserExperienceEntity> userExperiences) {
        this.userExperiences = userExperiences;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "UserEntity [userExperiences=" + userExperiences + ", userId=" + userId + ", prefix=" + prefix
                + ", firstName=" + firstName + ", lastName=" + lastName + ", middleName=" + middleName + ", userNumber="
                + userNumber + ", emailAddress=" + emailAddress + ", primaryContactNumber=" + primaryContactNumber
                + ", secondarayContactNumber=" + secondarayContactNumber + ", employeeCode=" + employeeCode
                + ", salary=" + salary + ", status=" + status + ", startDate=" + startDate + ", endDate=" + endDate
                + "]";
    }



}

我相信这是因为我引入了一些与hibernate相关的类,这些类导致了这个问题。有人能告诉我怎么了吗?

共有2个答案

鲁杜吟
2023-03-14

在这种情况下,似乎没有检测到包。你能试着用这个吗?

    @Column(name="CREATED_DATE", updatable=false, nullable=false)
    @CreationTimestamp 
    private java.sql.Timestamp createdDate;

编辑:

移除@Temporal。

或者保留Temporal,把包放在上面,就像:

@Column(name="CREATED_DATE", updatable=false, nullable=false)
@CreationTimestamp 
@Temporal(TemporalType.TIMESTAMP)
private java.util.Calendar createdDate;
周意智
2023-03-14

在我的例子中,我和org都面临着同样的错误。冬眠cfg。尝试编译以下Jpa文件时出现NotYetImplementedException

>

  • AlertJpaMode.java

      @Entity
      @Table(name = "alerts")
      @IdClass(AlertId.class)
      public class AlertJpaModel implements Serializable {
    
      /**
       *
       */
      private static final long serialVersionUID = 1L;
    
      @Id
      @Column(nullable = false)
      @CreationTimestamp
      private Instant timestamp;
    
      // more fields here and constructors + getters/setters
      }
    

    AlertId.java

    public class AlertId implements Serializable {
          /**
           *
           */
          private static final long serialVersionUID = 1L;
    
          private Instant timestamp;
          // more fields here and constructors + getters/setters
          }
    

    我只是把creationtimestap放在AlertId中。java而不是在AlertJpaMode中。java如下所示:

    >

  • AlertJpaMode.java

      @Entity
      @Table(name = "alerts")
      @IdClass(AlertId.class)
      public class AlertJpaModel implements Serializable {
    
      /**
       *
       */
      private static final long serialVersionUID = 1L;
    
      @Id
      @Column(nullable = false)
      private Instant timestamp;
    
      // more fields here and constructors + getters/setters
      }
    

    AlertId.java

     public class AlertId implements Serializable {
    
          /**
           *
           */
          private static final long serialVersionUID = 1L;
    
          @CreationTimestamp
          private Instant timestamp;
          // more fields here and constructors + getters/setters
          }
    

    ...它成功了。

  •  类似资料:
    • 我正在使用Arquillian、JBoss、JPA/Hibernate、H2 DB和Maven运行测试。在我的测试persistence.xml文件中,我有: 目前,我有一个User类通过Hibernate注释映射到“users”表。 一切都快开始了。问题是Hibernate正在尝试执行: 但是模式“my_schema”不存在,所以它失败了(毕竟我是在运行内存中的数据库)。 我如何进入Hibern

    • 有些人在不同的问题上提到,如果数据库在执行之前不存在,就会发生这个错误,所以我手动创建了数据库,但仍然会出现这个错误。 编辑:这里是应用程序的跟踪日志。由于文本太多,我将其上传为文件:https://ufile.io/zuk69

    • 问题内容: 我一直在尝试使用JPA Hibernate和mysql整理与数据库的连接,但是由于某种原因,无论我尝试什么,在启动tomcat服务器时,我都会遇到相同的异常: 这是我的JPA配置类: } 在这一点上,我想不出要尝试的任何其他方法了。 编辑:这是整个堆栈跟踪 问题答案: 问题是您无法获得与MYSQL数据库的连接,因此引发错误,提示无法建立会话工厂。 请查看以下错误: 这表示没有得到。 请

    • 我正在使用Spring Boot,我将向您解释我所进行的过程,然后我将为您暴露我的问题: 我正在使用的数据库是postgres:因为我有一个包含多个表的富数据库,所以我应用了hibernate反向工程来生成hole实体,直到这一步一切都很棒! 问题,在运行项目时,它就像是spring-data JPA和hibernate之间的混淆! ps:在项目开始工作之前,我用一张桌子做了一些实验,它工作得很好