title: Hibernate and Spring - Database tables not being automatically created
body: <p>I have been trying to use Spring and Hibernate together. At the moment I am trying to make Hibernate create the tables automatically. According to the documentation and examples I have found online, this should be achievable by setting the <code>hibernate.hbm2ddl.auto</code> to <code>create</code>, <code>create-drop</code> or <code>update</code>. For some reason this is not working. Below is where I am declaring my beans (in <code>\WEB-INF\dispatcher-servlet.xml</code>):</p>
  
  <pre><code>&lt;bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close"&gt;
      &lt;property name="driverClassName" value="com.mysql.jdbc.Driver" /&gt;
      &lt;property name="url" value="jdbc:mysql://localhost:3306/MY_SHOP" /&gt;
      &lt;property name="username" value="root" /&gt;
      &lt;property name="password" value="root" /&gt;
  &lt;/bean&gt;
  
  
  &lt;bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;
      &lt;property name="dataSource" ref="myDataSource" /&gt;
      &lt;property name="annotatedClasses"&gt;
          &lt;list&gt;
              &lt;value&gt;com.crimsonwing.dto.UserDTO&lt;/value&gt;
          &lt;/list&gt;
      &lt;/property&gt;
      &lt;property name="hibernateProperties"&gt;
          &lt;props&gt;
              &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQL5Dialect&lt;/prop&gt;
              &lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt;
          &lt;/props&gt;
      &lt;/property&gt;
  
  &lt;/bean&gt;
  
  &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&gt;
      &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="transactionManager"
      class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt;
      &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>This is how I am declaring my DTO:</p>
  
  <pre><code>@Entity
  @Table(name = "USER", uniqueConstraints = @UniqueConstraint(columnNames = { "EMAIL", "UID" }))
  public class UserDTO implements Serializable
  {
  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  
  // Validation Annotation
  @Size(min = 8, max = 30, message = "User name must be between 8 and 30 characters long.")
  // Database Anotation
  @Column(name = "NAME", insertable = true, updatable = true, nullable = false)
  private String name;
  
  // Validation Annotation
  @NumberFormat(style = Style.NUMBER)
  @Min(1)
  @Max(99)
  // Database Anotation
  @Column(name = "AGE", insertable = true, updatable = true, nullable = false)
  private int age;
  
  // Validation Annotation
  @UniqueEmail
  @Email(message = "Email is incorrect format.")
  @NotEmpty(message = "Email cannot be left empty")
  // Database Anotation
  @Column(name = "EMAIL", insertable = true, updatable = true, nullable = false)
  private String email;
  
  // Database Anotation
  @Id
  @Column(name = "UID", insertable = false, updatable = false, nullable = false)
  @GeneratedValue()
  private String userUID;
  
  public UserDTO(String name, int age, String email)
  {
      super();
      this.name = name;
      this.age = age;
      this.email = email;
  }
  
  public UserDTO()
  {
      /* WILL BE USED BY HIBERNATE */
  }
  
  ...
  </code></pre>
  
  <p>And this is how I am trying to access the database:</p>
  
  <pre><code>@Repository
  public class UserDAOImpl implements IUserDAO
  {
      @Resource
      private HibernateTemplate hibernateTemplate;
  
      @Override
      public bbolean userExists(String userEmail)
      {
          UserDTO user = new UserDTO();
          user.setEmail(userEmail);
  
          DetachedCriteria detachedCriteria = DetachedCriteria.forClass(user.getClass());
  
          return (this.hibernateTemplate.findByCriteria(detachedCriteria).size() &gt; ) ? true : false;
      }
  ...
  </code></pre>
  
  <p>Anyone can point me out in the right direction? Is there a missing setting or something I did wrong? I am using MySQL version <code>5.1.58-1ubuntu1</code> on an Ubuntu x64 platform with spring 3.1 and hibernate 3.6.10.</p>
  
  <p>Thanks.</p>
  
  <p>EDIT: Stacktrace added for completeness:</p>
  
  <pre><code>com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'MY_SHOP.USER' doesn't exist
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
      at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
      at com.mysql.jdbc.Util.getInstance(Util.java:386)
      at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
      at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
      at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
      at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
      at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
      at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
      at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
      at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
      at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
      at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
      at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
      at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
      at org.hibernate.loader.Loader.doQuery(Loader.java:802)
      at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
      at org.hibernate.loader.Loader.doList(Loader.java:2542)
      at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
      at org.hibernate.loader.Loader.list(Loader.java:2271)
      at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
      at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
      at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
      at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1056)
      at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1)
      at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
      at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
      at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1046)
      at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1039)
      at com.crimsonwing.dao.impl.UserDAOImpl.userExists(UserDAOImpl.java:36)
      at com.crimsonwing.service.impl.UserServiceImpl.userExists(UserServiceImpl.java:28)
      at com.crimsonwing.facades.impl.UserFacadeImpl.userExists(UserFacadeImpl.java:34)
      at com.crimsonwing.validator.uniqueemail.impl.UniqueEmailValidator.isValid(UniqueEmailValidator.java:26)
      at com.crimsonwing.validator.uniqueemail.impl.UniqueEmailValidator.isValid(UniqueEmailValidator.java:1)
      at org.hibernate.validator.engine.ConstraintTree.validateSingleConstraint(ConstraintTree.java:278)
      at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:153)
      at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:117)
      at org.hibernate.validator.metadata.MetaConstraint.validateConstraint(MetaConstraint.java:84)
      at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:452)
      at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:397)
      at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:361)
      at org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:313)
      at org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:139)
      at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:101)
      at org.springframework.validation.DataBinder.validate(DataBinder.java:722)
      at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:154)
      at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:107)
      at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:74)
      at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:155)
      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
      at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
      at java.lang.Thread.run(Thread.java:662)
  </code></pre>
  
  <p>Edit:</p>
  
  <p>As per parasietje's suggestion, this is the resulting HQL:
  <code>Hibernate: select this_.UID as UID2_0_, this_.AGE as AGE2_0_, this_.EMAIL as EMAIL2_0_, this_.NAME as NAME2_0_ from USER this_</code></p>
  
  <p>I do not get any other HQL. If I remember correctly, when the table is being created you also get to see the resulting HQL statement, which is not what is happening in this case.</p>