spring – Auto generate database from Hibernate model

Question:

There is a model and configuration for spring. It is necessary to automatically create a base from the model. But it is not created despite the fact that hbm2ddl.auto and annotatedClasses are set (when trying to save something to the database, an error is thrown that the table was not created). Any ideas what you can do? Thanks in advance.

@Entity
@Table(name = "advertisement", schema = "public")
public class Advertisement {

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

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

@Column(name = "picture_url")
@NotNull
@URL
private String pictureUrl;

@Column(name = "link_url")
@NotNull
@URL
private String linkUrl;

@Column(name = "state")
@Pattern(regexp = "(Active|Stopped|Pending)")
private String state = "Stopped";

@ManyToOne(optional = false)
@JoinColumn(name = "id_category", nullable = false)
private Category category;

@OneToMany(mappedBy = "add", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@Valid
private Set<Statistic> statistics;
//setters gettesr
}

@Entity
@Table(name = "category", schema = "public")

public class Category {

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

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

@Column(name = "state")
@Pattern(regexp = "(Active|Stopped|Pending)")
private String state = "Stopped";

@OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JsonIgnore
private Set<Advertisement> ads;
//setters getters
}

@Entity
@Table(name = "statistic", schema = "public")
public class Statistic {

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

@Column(name = "date")
@NotNull
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;

@Column(name = "clicks")
@NotNull
private int clicks;

@Column(name = "paid")
@NotNull
private int paid ;
//setters getters
}



   <tx:annotation-driven transaction-manager="transactionManager"/>

<context:component-scan base-package="sptool.managers"/>
<context:component-scan base-package="sptool.dao"/>
<context:component-scan base-package="sptool.controller"/>
<context:component-scan base-package="sptool.model"/>


<context:annotation-config></context:annotation-config>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>

    <property name="hibernateProperties">
        <props>
            <prop key="dialect">org.hibernate.dialect.PostgreSQL9Dialect</prop>
            <prop key="show_sql">true</prop>
            <prop key="hbm2ddl.auto">create</prop>
            <prop key="current_session_context_class">thread</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>sptool.model.Advertisement</value>
            <value>sptool.model.Category</value>
            <value>sptool.model.Statistic</value>
        </list>
    </property>

</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/>

Logs:

    2016-06-13 15:42:40.172  INFO 17462 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.5.Final}
2016-06-13 15:42:40.177  INFO 17462 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2016-06-13 15:42:40.180  INFO 17462 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2016-06-13 15:42:40.480  INFO 17462 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2016-06-13 15:42:40.492  INFO 17462 --- [           main] o.h.e.jdbc.internal.LobCreatorBuilder    : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2016-06-13 15:42:40.640  INFO 17462 --- [           main] o.h.e.t.i.TransactionFactoryInitiator    : HHH000399: Using default transaction strategy (direct JDBC transactions)
2016-06-13 15:42:40.644  INFO 17462 --- [           main] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2016-06-13 15:42:41.239  INFO 17462 --- [           main] o.s.c.s.ClassPathXmlApplicationContext   : Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32fa809f: startup date [Mon Jun 13 15:42:41 CEST 2016]; root of context hierarchy
2016-06-13 15:42:41.240  INFO 17462 --- [           main] o.s.b.f.xml.XmlBeanDefinitionReader      : Loading XML bean definitions from class path resource [bean_configuration.xml]
2016-06-13 15:42:41.507  INFO 17462 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'org.springframework.transaction.config.internalTransactionAdvisor' with a different definition: replacing [Root bean: class [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration; factoryMethodName=transactionAdvisor; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]]
2016-06-13 15:42:41.507  INFO 17462 --- [           main] a.ConfigurationClassBeanDefinitionReader : Skipping bean definition for [BeanMethod:name=transactionalEventListenerFactory,declaringClass=org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration]: a definition for bean 'org.springframework.transaction.config.internalTransactionalEventListenerFactory' already exists. This top-level bean definition is considered as an override.
2016-06-13 15:42:41.532  INFO 17462 --- [           main] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: org.postgresql.Driver
2016-06-13 15:42:41.667  INFO 17462 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2016-06-13 15:42:41.668  INFO 17462 --- [           main] o.h.e.jdbc.internal.LobCreatorBuilder    : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2016-06-13 15:42:41.676  INFO 17462 --- [           main] o.h.e.t.i.TransactionFactoryInitiator    : HHH000399: Using default transaction strategy (direct JDBC transactions)
2016-06-13 15:42:41.677  INFO 17462 --- [           main] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2016-06-13 15:42:41.726  INFO 17462 --- [           main] o.s.c.s.ClassPathXmlApplicationContext   : Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@16da476c: startup date [Mon Jun 13 15:42:41 CEST 2016]; root of context hierarchy
2016-06-13 15:42:41.727  INFO 17462 --- [           main] o.s.b.f.xml.XmlBeanDefinitionReader      : Loading XML bean definitions from class path resource [bean_configuration.xml]
2016-06-13 15:42:42.023  INFO 17462 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'org.springframework.transaction.config.internalTransactionAdvisor' with a different definition: replacing [Root bean: class [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration; factoryMethodName=transactionAdvisor; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]]
2016-06-13 15:42:42.024  INFO 17462 --- [           main] a.ConfigurationClassBeanDefinitionReader : Skipping bean definition for [BeanMethod:name=transactionalEventListenerFactory,declaringClass=org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration]: a definition for bean 'org.springframework.transaction.config.internalTransactionalEventListenerFactory' already exists. This top-level bean definition is considered as an override.
2016-06-13 15:42:42.040  INFO 17462 --- [           main] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: org.postgresql.Driver
2016-06-13 15:42:42.131  INFO 17462 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2016-06-13 15:42:42.132  INFO 17462 --- [           main] o.h.e.jdbc.internal.LobCreatorBuilder    : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2016-06-13 15:42:42.141  INFO 17462 --- [           main] o.h.e.t.i.TransactionFactoryInitiator    : HHH000399: Using default transaction strategy (direct JDBC transactions)
2016-06-13 15:42:42.142  INFO 17462 --- [           main] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2016-06-13 15:42:42.225  INFO 17462 --- [           main] o.s.o.h.HibernateTransactionManager      : Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@5234b61a] of Hibernate SessionFactory for HibernateTransactionManager
2016-06-13 15:42:42.545  INFO 17462 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-06-13 15:42:42.565  INFO 17462 --- [           main] o.s.o.h.HibernateTransactionManager      : Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@5aa76ad2] of Hibernate SessionFactory for HibernateTransactionManager
2016-06-13 15:42:42.738  INFO 17462 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-06-13 15:42:42.750  INFO 17462 --- [           main] o.s.o.h.HibernateTransactionManager      : Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@2871ac91] of Hibernate SessionFactory for HibernateTransactionManager
2016-06-13 15:42:42.878  INFO 17462 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-06-13 15:42:43.076  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4b9e255: startup date [Mon Jun 13 15:42:36 CEST 2016]; root of context hierarchy
2016-06-13 15:42:43.170  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/{id}/advertisement/],methods=[POST],produces=[application/json]}" onto public org.springframework.http.ResponseEntity sptool.controller.AdvertisementController.createAd(int,sptool.model.Advertisement)
2016-06-13 15:42:43.172  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/advertisement/{id}],methods=[GET]}" onto public org.springframework.http.ResponseEntity sptool.controller.AdvertisementController.getAdById(int)
2016-06-13 15:42:43.172  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/{id}/advertisement],methods=[GET]}" onto public org.springframework.http.ResponseEntity sptool.controller.AdvertisementController.getAdsFromCategory(int,java.util.List<java.lang.String>)
2016-06-13 15:42:43.172  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/advertisement/{id}],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<java.lang.Void> sptool.controller.AdvertisementController.removeAd(int)
2016-06-13 15:42:43.173  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/advertisement/{id}/statistic],methods=[POST]}" onto public org.springframework.http.ResponseEntity sptool.controller.StatisticController.createStatistic(int,sptool.model.Statistic)
2016-06-13 15:42:43.174  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/advertisement/{id}/general],methods=[GET]}" onto public org.springframework.http.ResponseEntity sptool.controller.StatisticController.generalStatistic(int,java.lang.String,java.lang.String)
2016-06-13 15:42:43.174  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/{id}/statistic],methods=[GET]}" onto public org.springframework.http.ResponseEntity sptool.controller.StatisticController.generalStatisticAboutCategory(int,java.lang.String,java.lang.String)
2016-06-13 15:42:43.175  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/{id}],methods=[GET]}" onto public org.springframework.http.ResponseEntity sptool.controller.CategoryController.getCategory(int)
2016-06-13 15:42:43.176  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/],methods=[GET]}" onto public org.springframework.http.ResponseEntity sptool.controller.CategoryController.listAllCategories()
2016-06-13 15:42:43.176  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/],methods=[POST],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<java.lang.String> sptool.controller.CategoryController.createCategory(sptool.model.Category)
2016-06-13 15:42:43.176  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/{id}],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity sptool.controller.CategoryController.removeCategory(int)
2016-06-13 15:42:43.176  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/category/{id}],methods=[PUT]}" onto public org.springframework.http.ResponseEntity sptool.controller.CategoryController.updateCategory(int,sptool.model.Category)
2016-06-13 15:42:43.181  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-06-13 15:42:43.181  INFO 17462 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-06-13 15:42:43.212  INFO 17462 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-06-13 15:42:43.213  INFO 17462 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-06-13 15:42:43.260  INFO 17462 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-06-13 15:42:43.344  INFO 17462 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
2016-06-13 15:42:43.644  INFO 17462 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-06-13 15:42:43.810  INFO 17462 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-06-13 15:42:43.838  INFO 17462 --- [           main] sptool.controller.App                    : Started App in 7.667 seconds (JVM running for 8.13)
2016-06-13 15:42:46.400  INFO 17462 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-06-13 15:42:46.400  INFO 17462 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-06-13 15:42:46.412  INFO 17462 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms
2016-06-13 15:42:46.623  WARN 17462 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42P01
2016-06-13 15:42:46.623 ERROR 17462 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: relation "public.category" does not exist

Answer:

  1. Make sure you can connect to the database at all with the specified JDBC URL and user;

  2. You probably took a Spring Boot application and copied a piece of Spring MVC XML config into it. XML is not needed there at all. It's usually done like this;

  3. To understand what is happening with the application, the logs need to be filmed in DEBUG.

Look in the logs. You are connecting to H2 Starting embedded database: url = 'jdbc: h2: mem: testdb; DB_CLOSE_DELAY = -1; DB_CLOSE_ON_EXIT = false', username = 'sa' although, judging by the hibernate setting, you want to connect to PostgreSQL. This can be, if the DataSource is not configured, the DataSource for H2 is created by default. So creating a DataSource connecting to Postgres and declaring it as a bean might solve your problem

Scroll to Top