0

Full stacktrace:

     GenerationTarget encountered exception accepting command : Error executing DDL "create table employee (id integer generated by default as identity, email varchar(255), first_name varchar(255), last_name varchar(255), employee_detail_id integer, primary key (id))" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table employee (id integer generated by default as identity, email varchar(255), first_name varchar(255), last_name varchar(255), employee_detail_id integer, primary key (id))" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135)
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:615)
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:545)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:203)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1441)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1240)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5343)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5588)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:516)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:877)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:860)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:644)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2020)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1666)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:83)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:98)

DemoAppConfig class:

     @Configuration
@EnableWebMvc
@ComponentScan
@EnableTransactionManagement
@PropertySource("classpath:persistence-mysql.properties")
public class DemoAppConfig implements WebMvcConfigurer {


    @Autowired
    private Environment env;

    private Logger logger = Logger.getLogger(getClass().getName());

    @Bean
    public DataSource dataSource() {

        // create connection pool
        ComboPooledDataSource myDataSource = new ComboPooledDataSource();

        // set the jdbc driver
        try {
            myDataSource.setDriverClass("com.mysql.jdbc.Driver");
        }
        catch (PropertyVetoException exc) {
            throw new RuntimeException(exc);
        }

        // for sanity's sake, let's log url and user ... just to make sure we are reading the data
        logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
        logger.info("jdbc.user=" + env.getProperty("jdbc.user"));

        // set database connection props
        myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
        myDataSource.setUser(env.getProperty("jdbc.user"));
        myDataSource.setPassword(env.getProperty("jdbc.password"));

        // set connection pool props
        myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
        myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
        myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
        myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));

        return myDataSource;
    }

    private Properties getHibernateProperties() {

        // set hibernate properties
        Properties props = new Properties();

        props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));

        return props;
    }


    // need a helper method
    // read environment property and convert to int

    private int getIntProperty(String propName) {

        String propVal = env.getProperty(propName);

        // now convert to int
        int intPropVal = Integer.parseInt(propVal);

        return intPropVal;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(
                new String[]{"ets.entity"});
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public PlatformTransactionManager hibernateTransactionManager() {
        HibernateTransactionManager transactionManager
                = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }

    private final Properties hibernateProperties() {
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty(
                "hibernate.hbm2ddl.auto", "create-drop");
        hibernateProperties.setProperty(
                "hibernate.dialect", "org.hibernate.dialect.H2Dialect");

        return hibernateProperties;
    }

}

Class Employee:

  package ets.entity;

import javax.persistence.*;

@Entity
@Table(name="employee")
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

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

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

    @Column(name = "email")
    private String email;

    @OneToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE,
            CascadeType.DETACH, CascadeType.REFRESH})
    @JoinColumn(name = "employee_detail_id")
    private EmployeeDetail employeeDetail;

    public Employee() {
    }

    public Employee(int id, String firstName, String lastName, String email, EmployeeDetail employeeDetail) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.employeeDetail = employeeDetail;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public EmployeeDetail getEmployeeDetail() {
        return employeeDetail;
    }

    public void setEmployeeDetail(EmployeeDetail employeeDetail) {
        this.employeeDetail = employeeDetail;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", employeeDetail=" + employeeDetail +
                '}';
    }
}

Class employeeDetail

      package ets.entity;

import javax.persistence.*;

@Entity
@Table(name = "employee_detail")
public class EmployeeDetail {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="work_experience")
    private int workExperience;

    @Column(name="hobby")
    private int hobby;

    @Column(name="language")
    private int language;

    @OneToOne(mappedBy = "employee")
private Employee employee;

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public EmployeeDetail() {
    }

    public EmployeeDetail(int workExperience, int hobby, int language) {
        this.workExperience = workExperience;
        this.hobby = hobby;
        this.language = language;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getWorkExperience() {
        return workExperience;
    }

    public void setWorkExperience(int workExperience) {
        this.workExperience = workExperience;
    }

    public int getHobby() {
        return hobby;
    }

    public void setHobby(int hobby) {
        this.hobby = hobby;
    }

    public int getLanguage() {
        return language;
    }

    public void setLanguage(int language) {
        this.language = language;
    }

    @Override
    public String toString() {
        return "EmployeeDetail{" +
                "id=" + id +
                ", workExperience=" + workExperience +
                ", hobby=" + hobby +
                ", language=" + language +
                ", employee=" + employee +
                '}';
    }
}

What is problem with sessiono factory? If u need more of my code I will share

  • You have a `NullPointerException`, seemingly in code you've not shared. What is happening in `ConstructorResolver.java`, line 587? See the following in your stack trace: `at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)` – ScottWelker Sep 02 '21 at 14:12
  • That is not my class, nvm this is part of code: `throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via factory method failed", ex); }` – Stefan Jankovic Sep 02 '21 at 14:14
  • If you can step through (trace) the code you'll find something is unexpectedly null. Best help can give without the code. Perhaps others can be more helpful. – ScottWelker Sep 02 '21 at 14:15
  • Why you have annotated both `@Bean` and `@Autowired` `transactionManager`? Can you try removing the `@Autowired` annotation from this bean? – pleft Sep 02 '21 at 14:22
  • Now im gettng this error: ` Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ets.config.DemoAppConfig: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unknown mappedBy in: ets.entity.EmployeeDetail.employee, referenced property unknown: ets.entity.Employee.employee]] ` – Stefan Jankovic Sep 02 '21 at 14:22
  • You have to post also your Entities (Employee, EmployeeDetail etc) – pleft Sep 02 '21 at 14:24
  • I updated my question now with that classes, also with new app config and stack trace – Stefan Jankovic Sep 02 '21 at 14:26

1 Answers1

0

For this error:

 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ets.config.DemoAppConfig: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unknown mappedBy in: ets.entity.EmployeeDetail.employee, referenced property unknown: ets.entity.Employee.employee

Try changing the mappedBy in @OneToOne annotation in EmployeeDetail to:

@OneToOne(mappedBy = "employeeDetail")
private Employee employee;
pleft
  • 7,567
  • 2
  • 21
  • 45
  • Its fine now about this, but new error is `org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table employee_detail if exists" via JDBC Statement ` – Stefan Jankovic Sep 02 '21 at 14:34
  • Should be more following this error please post full info, for example check this https://stackoverflow.com/questions/43191294/hibernate-error-executing-ddl-via-jdbc-statement/49573003 – pleft Sep 02 '21 at 14:52
  • 1
    There is no "Caused by..." in you stacktrace? Please post full stacktrace. However this kind of error is totally different than the one in your initial question. Please if your initial problem is solved consider accepting the correct answer and post another question about your new error. Now you have edited your question post and the stacktrace you have does not reflect to your actual initial error/problem and it is confusing for other community members who also search for solutions to similar problems. – pleft Sep 02 '21 at 15:46