0

I am working with Hibernate with spring boot. I have noticed that if I include the annotation @CreationTimestamp and @UpdateTimestamp from the package

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

on the AuditEntity and try to run the spring boot application. My application startup fails with the below error.

""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

the moment I remove these annotation and try to run the application. the application starts up fine.

AuditEntity.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;
    }


}

Pom.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>

I am embedding the audit entity into the userentity.

below is the code for 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
                + "]";
    }



}

I believe its because i am introducing some hibernate related classes which is causing this issue. Can someone please let me know whats wrong ?

2 Answers 2

1

In my case, I was facing the same error, together with org.hibernate.cfg.NotYetImplementedException when trying to compile the following Jpa files:

  • 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
          }
    

I simply put CreationTimestamp in AlertId.java instead of in AlertJpaMode.java as follows:

  • 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
          }
    

...and it worked.

Sign up to request clarification or add additional context in comments.

Comments

0

It seems the package is not detected in this case. Can you try to use this?

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

Edit:

Remove the @Temporal.

Or keep the Temporal and put the package to it like:

@Column(name="CREATED_DATE", updatable=false, nullable=false)
@CreationTimestamp 
@Temporal(TemporalType.TIMESTAMP)
private java.util.Calendar createdDate;

6 Comments

nope.. i get this error Caused by: org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property: com.niti.dao.entity.AuditEntity.createdDate
the defination of TemporalType states that javax.persistence.TemporalType Type used to indicate a specific mapping of java.util.Date or java.util.Calendar. So java.sql.timestamp would never work.. but still i tried and got the error above
@user641887: can you try that?!
i tried that .. below is the code what i tried @ Column(name="CREATED_DATE", updatable=false, nullable=false) @ CreationTimestamp @ Temporal(TemporalType.TIMESTAMP) private java.util.Calendar createdDate; @ Column(name="LAST_UPDATED_DATE", nullable=false) @ UpdateTimestamp @ Temporal(TemporalType.TIMESTAMP) private java.util.Calendar lastUpdatedDate; still same error
@ user641887: So strange. I've just tested with the code like and it is working fine: @Temporal(TemporalType.TIMESTAMP) @Column(name="CREATED", insertable = false,updatable=false, nullable=false) @CreationTimestamp private java.util.Calendar createdDate;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.