Skip to main content

Rest API using Spring and Hibernate connecting to a PostgreSQL database



In my last post Setting up a Postgresql database, I showed how to install and setup a simple postgres local database. Now I am going to proceed and create a simple java Spring project that exposes a rest api endpoint allowing to query and fetch data from the database.

The IDE i am using is Eclipse and I will be using Maven for building the project.

To start create a Maven project using the archetype - maven-archetype-webapp.
In Eclipse, I enable Dynamic Web Module Facet in the project's properties and set the compiler level to 1.7 at least.



  • Update the pom.xml file to add required dependencies. For our project, we will use spring-webmvc , javax.servlet-api, jackson-core and jackson-databind. These are required to build a rest api endpoing with automatic conversion of java objects to json and vice versa.
  • Also add following dependencies to enable persistence with the postgreSQL database - spring-data-jpa, hibernate-entitymanager, postgresql and jta. 



  • Now that we got all our dependencies added, lets start building the project. I will start by setting up my project to talk to the database via Spring data and Hibernate for JPA.
  • In project, I created a package "org.rajesh.learning.UserSpringMVCPostgres.Config" and added a class "DBConfig".
  • In that class, I am going to create beans for LocalContainerEntityManagerFactoryBean, DataSource and a PlatformTransactionManager. As you will notice I am going to use java class based configuration for my JPA instead of XML. The class will look like below - 
      As you can see above, first I indicate this class is a configuration class by using annotation @Configuration and then annotation  @Bean to create all the beans i mentioned earlier.


Also I am using two other annotations to enable Spring data JPA capabilities for transaction management and recognizing which package has my JPA repository definitions.

Couple of other important things that i did - In the datasource class and the entityManager, I setup all the required properties for connecting to my postgres database. Also I indicate which package to scan to find my entities.

  • Next let me setup the class for my data Model. From my previous tutorial on the database setup Setting up a Postgresql database, you will remember there is a table "users" with colums - firstname, lastname and login.
  • So I created a class "User" in a package org.rajesh.learning.UserSpringMVCPostgres.Model as shown below 

 
    As you will notice I used annotations @Table and @Column to tie my class with the database table. Otherwise this is a simple POJO.
  • Next lets create the Repository that will support the basic CRUD operations. Here is where Spring Data comes into play. Just by adding a CRUDRepository interface, we can get this functionality. That is the power of using a framework like Spring!
   
      I have annotated it with @Repository to indicate this is a repository. You will notice I have not implemented any abstract methods in it. So we will just use the methods that the interface will provide us. For ex: findAll()
  • Now that we have done everything to support our java persistence, lets move on to setting up the rest api endpoint. First let me set up the WebApplicationInitializer. I am not going to setup the servlet using the web.xml and will use the WebApplicationInitializer interface instead. I believe this is part of the Servlet 3.0 specification.
  I am using a AnnotationConfigWebApplicationContext object to set the context of the servlet dispatcher. I indicate the package where my Configuration exists using setConfigLocation method.

  • Now lets setup some configuration classes. I will setup a AppConfig class and indicate that the package to scan for generating beans via the @ComponentScan annotation. Also I setup another Config class with @EnableWebMvc annotation. This imports the Spring MVC configuration to the project.



  • Now lets setup the Rest Controller class that will expose our end point. For this demo, i will just setup one simple GET method and use the findAll() repository event.
   As you can see in the code, I have used @RestController to indicate this is my rest controller class. I am auto wiring my CRUDRepository into this controller. After that I create the method that supports the GET method and indicate it with the @RequestMapping annotation.

Thats it, my project is setup. Next I built the project using maven - mvn clean install command. Then I deployed the project to my local Tomcat 8 server.

Here are the results -

Cool, we have a simple api setup minus features like authentication. Next I intend to develop this a bit further and then use it in my Salesforce org. I would like to switch over to Salesforce to make some http callouts and explore Apex a bit. Till then, enjoy folks!


Comments

Popular posts from this blog

Workaround to bypass Salesforce SSO

One of the best practices for implementing Single Sign On for your Salesforce org is always ensure there is a way your System administrator can login via the standard login page side-stepping the SSO configuration.  Reason for this is if ever something goes wrong with your Idp provider's service and the SSO authentication responses are not coming as expected, all your users are unable to login. That is, if you have setup your My domain to prevent logins via standard Salesforce login urls (login.salesforce.com). This includes the System administrator as well. Only if your system administrator can somehow login, then he or she can disable the SSO settings for your domain and allow login via the normal login page as a temporary measure. What do you do in such a situation? Well Salesforce has built a workaround for this which is not well documented anywhere (probably for a good reason :) ). I found out about it from a colleague at work. If your my domain url is - https://Com

Salesforce Big Objects - Key learnings

I remember reading about Salesforce Big Objects before they became available and thought maybe it is an option to backup data present in regular objects. That is, instead of taking a backup via an ETL tool or data loader, maybe this will be an option to backup the data in the Force.com platform itself. Now that it is GA and I am reading more about it, i think the use cases for this are more varied. Some use cases I can think of are –  Archival of key data objects within the platform: You may want to use this option if you dont use any other means to backup key data. Also this may be an attractive option for non-large enterprise customers who dont themselves invest on large data warehouses or data lakes in their enterprise architecture. Ex: customer history (if present in tasks and activities) will become huge over years but this is useful information for reporting & customer analysis. Store key information which is large volume in quantity and also high volume in transa

DBAmp for Salesforce - salesforce integration for SQL Server DBAs

Recently i got the opportunity to explore a tool called DBAmp for integration with Salesforce. I found it to be a very useful tool which will help with any data manipulation requirements in Salesforce. Following are my learnings from the exercise. Hope it helps any of you who may need to work with this tool -  DBAmp is a SQL Server package that can be used to integrate with Salesforce. The site where this software is available is - http://www.forceamp.com/ Overview: It essentially installs on top of an existing SQL Server database and provides an OLE DB connector that can be used to connect to Salesforce. Behind the scenes, it executes API calls against Salesforce for any SQL server command it receives. Thus we can create a connection in SQL server to Salesforce org and pull data into tables in the database just as if we are querying against Salesforce tables directly. Use cases for DBAmap + Salesforce: Many use cases exist for using this tool against Salesforce. Pr