Book Image

Spring Cookbook

Book Image

Spring Cookbook

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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>
      <version>5.1.35</version>
    </dependency>
  3. If you're using PostgreSQL, add its Maven dependency in pom.xml:

    <dependency>
      <groupId...