title: Spring Data config and Postgres database integration (NO xml configuration)
body: <p>I have a project based on Spring Framework and it is initialized based only on Java configuration. This means that there is no need to use a <em>web.xml</em> file. </p>
  
  <p>You can see the project's structure in the following image:</p>
  
  <p><a href="https://i.stack.imgur.com/GuCR1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GuCR1.png" alt="enter image description here"></a></p>
  
  <h2>TECHNOLOGIES USED:</h2>
  
  <ul>
  <li>Java 7 </li>
  <li>Spring framework 4.2.1.RELEASE </li>
  <li>Hibernate ORM 5.0.4.Final</li>
  <li>Spring Tool Suite IDE 3.6.2 </li>
  <li>Maven 3 </li>
  <li>Tomcat 7</li>
  </ul>
  
  <h2>Initialization Configuration Files</h2>
  
  <p>The "main" class is called AppInitializer and it resides under the <em>initializer</em> folder</p>
  
  <p><strong>AppInitializer</strong></p>
  
  <pre><code>public class AppInitializer implements WebApplicationInitializer {
  
      private static final String CONFIG_LOCATION = "com.project.app.config";
      private static final String MAPPING_URL = "/";
  
      @Override
      public void onStartup(ServletContext servletContext) throws ServletException {
  
          // Create the 'root' Spring application context
          WebApplicationContext context = getContext();
  
          // Manage the lifecycle of the root application context
          servletContext.addListener(new ContextLoaderListener(context));
  
          // Register and map the dispatcher servlet
          ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
                  new DispatcherServlet(context));
          dispatcher.setLoadOnStartup(1);
          dispatcher.addMapping(MAPPING_URL);
  
      }
  
      private AnnotationConfigWebApplicationContext getContext() {
          AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
          context.setConfigLocation(CONFIG_LOCATION);
  
          return context;
      }
  
  }
  </code></pre>
  
  <p>..while my configuration classes reside in the <em>config</em> folder</p>
  
  <p><strong>WebMvcConfig</strong></p>
  
  <pre><code>@EnableWebMvc
  @Configuration
  @ComponentScan(basePackages = { "com.project.app" })
  public class WebMvcConfig extends WebMvcConfigurerAdapter {
  
      @Autowired
      private Environment env;
  
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
      }
  
      @Override
      public void addViewControllers(ViewControllerRegistry registry) {
          registry.addViewController("/").setViewName("hello");
      }
  
      @Bean
      public ApplicationContextProvider applicationContextProvider() {
          return new ApplicationContextProvider();
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>Database Configuration Files</h2>
  
  <p>At this point i want to add a <em>postgres</em> database in my project, therefore i created a folder named <em>db</em> in the CONFIG_LOCATION and in this way spring will "pick up" the @Configuration classes.( After creating a new db using PGAdmin ).. i created the following configuration class.</p>
  
  <p><strong>DataSources</strong></p>
  
  <pre><code>@Component
  @PropertySource("classpath:application.properties")
  public class DataSources {
  
      @Autowired
      private Environment env;
  
      @Bean
      @Primary
      public DataSource dataSource() {
          org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
  
          String url = env.getProperty(SystemSettings.DS_URL);
          String user = env.getProperty(SystemSettings.DS_USERNAME);
          String pass = env.getProperty(SystemSettings.DS_PASSWORD);
  
          ds.setDriverClassName("org.postgresql.Driver");
          ds.setUrl(url);
          ds.setUsername(user);
          ds.setPassword(pass);
  
          return ds;
      }
  
  }
  </code></pre>
  
  <p>whereas <strong>SystemSettings</strong> holds the username,password and url of the Database</p>
  
  <pre><code>@Service
  @Configuration
  public class SystemSettings implements Settings {  
  
      public static final String DS_URL = "datasource.app.url";
      public static final String DS_USERNAME = "datasource.app.username";
      public static final String DS_PASSWORD = "datasource.app.password";
  
      @Autowired
      private Environment env;
  
      @Override
      public String get(String key) {
          return env.getProperty(key);
      }
  
  }
  </code></pre>
  
  <p>The values are picked up from an <em>application.properties</em> file as its denoted in the <em>DataSources</em> class.</p>
  
  <blockquote>
    <p>spring.jpa.database=POSTGRESQL<br>
    spring.jpa.show-sql=true<br>
    spring.jpa.hibernate.ddl-auto=update<br>
    datasource.app.type=POSTGRESQL<br>
    datasource.app.url=jdbc:postgresql://localhost:5432/app<br>
    datasource.app.username=user datasource.app.password=pass      </p>
  </blockquote>
  
  <h2>Entities and Repository</h2>
  
  <p>I proceed on adding an entity class that will represent a simple table in the project. 
  It is located inside the <em>services/entities</em> folder</p>
  
  <p><strong>StopJPA</strong></p>
  
  <pre><code>@Entity
  @Table(name = "stop")
  public class StopJPA {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "id")
      private Long id;
  
      @Column(name = "description")
      private String stopDescription;
  
      @Column(name = "idStop")
      private String idStop;
  
      public StopJPA() {
      }
  
      public StopJPA(String stopDescription, String idStop) {
          this.stopDescription = stopDescription;
          this.idStop = idStop;
      }
  
      public Long getId() {
          return id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      public String getStopDescription() {
          return stopDescription;
      }
  
      public void setStopDescription(String stopDescription) {
          this.stopDescription = stopDescription;
      }
  
      public String getIdStop() {
          return idStop;
      }
  
      public void setIdStop(String idStop) {
          this.idStop = idStop;
      }
  
  }
  </code></pre>
  
  <p>Then i created a repository interface for this table that extends a <em>CrudRepository</em>.</p>
  
  <p><strong>StopRepository</strong></p>
  
  <pre><code>/**
   * Repository interface for StopJPA entities.
   */
  @Repository
  @RepositoryRestResource(collectionResourceRel = "stop", path = "stop")
  public interface StopRepository extends CrudRepository&lt;StopJPA, Long&gt; {
  
      StopJPA findById(@Param("id") Long id);
  
  }
  </code></pre>
  
  <h2>Questions</h2>
  
  <p>After all this setup and configuration i managed to get the project running but the table is not created in the database. </p>
  
  <ul>
  <li>What am i missing in the configuration steps?</li>
  <li>How am i going to make Spring scan the JPA entity and create the database?</li>
  </ul>
  
  <hr>
  
  <p>My <strong><em>MAIN INTENTION</em></strong> is to configure Spring (by using <em>Spring Data JPA</em>) and Hibernate in order to make them work together without the use of xml configuration files and without Spring BOOT dependencies. The latter means that the environment has to be configured "manually".</p>
  
  <hr>
  
  <hr>
  
  <h2>UPDATE</h2>
  
  <p>I added some more configuration in the <em>DataSources</em> class and renamed it in</p>
  
  <p><strong>PersistenceContext</strong></p>
  
  <pre><code>@Component
  @EnableTransactionManagement
  @PropertySource("classpath:application.properties")
  public class PersistenceContext {
  
      @Autowired
      private Environment env;
  
      @Bean
      @Primary
      public DataSource dataSource() throws ClassNotFoundException {
          org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
  
          String url = env.getProperty(SystemSettings.DS_URL);
          String user = env.getProperty(SystemSettings.USERNAME);
          String pass = env.getProperty(SystemSettings.DS_PASSWORD);
  
          ds.setDriverClassName("org.postgresql.Driver");
          ds.setUrl(url);
          ds.setUsername(user);
          ds.setPassword(pass);
  
          return ds;
      }
  
      @Bean
      LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
          LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
          entityManagerFactoryBean.setDataSource(dataSource);
          entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
          entityManagerFactoryBean.setPackagesToScan("com.project.app.services.entities");
  
          Properties jpaProperties = new Properties();
  
          // Configures the used database dialect. This allows Hibernate to create SQL
          // that is optimized for the used database.
          jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
  
          // Specifies the action that is invoked to the database when the Hibernate
          // SessionFactory is created or closed.
          jpaProperties.put("hibernate.hbm2ddl.auto",
                  env.getRequiredProperty("hibernate.hbm2ddl.auto"));  
  
          // If the value of this property is true, Hibernate writes all SQL
          // statements to the console.
          jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
  
          // If the value of this property is true, Hibernate will format the SQL
          // that is written to the console.
          jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
  
          entityManagerFactoryBean.setJpaProperties(jpaProperties);
  
          return entityManagerFactoryBean;
      }
  
      /**
       * Because we are using JPA, we have to create a transaction manager bean that integrates the
       * JPA provider with the Spring transaction mechanism. We can do this by using the
       * JpaTransactionManager class as the transaction manager of our application.
       *
       * We can configure the transaction manager bean by following these steps:
       *
       * -&gt; Create a new JpaTransactionManager object. -&gt; Configure the entity manager factory whose
       * transactions are managed by the created JpaTransactionManager object.
       **/
      @Bean
      JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
          JpaTransactionManager transactionManager = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(entityManagerFactory);
          return transactionManager;
      }
  }
  </code></pre>
  
  <p>Ans ALSO updated the properties file </p>
  
  <blockquote>
    <p>hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect<br>
    hibernate.hbm2ddl.auto=create-drop hibernate.show_sql=false<br>
    hibernate.format_sql=true              </p>
    
    <p>datasource.app.type=POSTGRESQL<br>
    datasource.app.driverClassName=org.postgresql.Driver<br>
    datasource.app.url=jdbc:postgresql://localhost:5432/app<br>
    datasource.app.username=user datasource.app.password=pass</p>
  </blockquote>
  
  <p>Unfortunately now i get this error</p>
  
  <blockquote>
    <p>SEVERE: Unable to create initial connections of pool.
    java.sql.SQLException: org.postgresql.Driver  at
    ...... <strong>Caused by:</strong> java.lang.ClassNotFoundException:
    org.postgresql.Driver at......</p>
  </blockquote>
  
  <p>I dont know why it gives me this exception. The maven dependency is there, the driver is also in classpath. . Any help? </p>