Connecting to a database

In this recipe, we will connect to a MySQL or PostgreSQL database from a Spring application. To connect to another database system, go to http://www.oxygenxml.com/database_drivers.html to find the relevant dependencies, driver class, and URL type.

Getting ready

You need a MySQL or PostgreSQL database up and running.

How to do it…

Here are the steps to connect from a Spring application to an existing database:

  1. Add the Maven dependency for Spring JDBC in pom.xml:
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
  2. If you're using MySQL, add its Maven dependency in pom.xml:
    <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.