Thursday, 24 March 2016

Persisting your first record using Spring Data Project.

This post is continuing from the last Setup post of a Sprig Data project.

To Persist a record in the database we require an object, So lets write our Model Class.

package com.sd.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="CITY")
public class City {
   
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long cityId;
   
    @Column(name="CITY_NAME")
    private String name;
   
    @Column(name="CITY_POPULATION")
    private Long population;
    public Long getCityId() {
        return cityId;
    }
    public void setCityId(Long cityId) {
        this.cityId = cityId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Long getPopulation() {
        return population;
    }
    public void setPopulation(Long population) {
        this.population = population;
    }
   }

This model City class is simple to understand and does not require much explanation.



As explained in the first post, we need an interface to extend JpaRepository. So this is how we do it.



import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.sd.model.City;

@Repository
public interface CityRepository extends JpaRepository<City, Long> {

}

That will be enough to pick our Model and get the job started.




Write this basic code and you will get the  object persisted.


    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringDataApplication.class, args);
        CityRepository cr = context.getBean(CityRepository.class);
        cr.save(getCity());
    }
   
    private static City getCity(){
        City city = new City();
        city.setCityId(1l);
        city.setName("Shimla");
        city.setPopulation(100000l);
       
        return city;
       
    }

I will explain how this worked in the next post.

Creating a Simple Spring Data Project

To create a simple Spring Data Project in Spring Tool Set we can use a Spring starter project.

In STS create a new Spring Starter Project.

In the Maven POM file use:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>


        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

This will get you all the Spring Data dependencies,  and if you want to try out with and in memory database H2 will also be fetched.

Then in the project properties file in the resource folder, put the following configuration.

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
logging-level = DEBUG
spring.datasource.url = jdbc:h2:~/test
spring.datasource.username = sa
spring.datasource.password =

You will NOT require last three entries if you do not have a stanalone verioin of H2 database.

Thats it you now have a Spring Data Project with H2 database up and Running.

Why use Spring Data?

Spring wants to rule the entire enterprise development life-cycle, from being non-invasive framework which worked without getting your code being aware about it, to littering the code with @Autowire to @EnableMVC, Spring now is in every java source file. The dependency on spring is so much that there is no way of getting spring out of your enterprise code once it gets there.


So here comes Spring to provide you an improved way to access data with in your application by providing modules like;

    Spring Data Commons
    Spring Data JPA
    Spring Data MongoDB
    Spring Data Redis
    Spring Data KeyValue
    Spring Data Solr
    Spring Data REST
    Spring Data Neo4j (community module)
    Spring Data Cassandra (community module)
    Spring Data Couchbase (community module)
    Spring Data Elasticsearch (community module)

This covers most of the data sources you will find out there, and simplifies the configuration you will need to write down to access these data sources greatly.



The   Hibernate paging feature comes to you with the Repository.


Now just to make life a bit easier for the developers, Spring Data allows you to write queries specific to the underlying data data store. You use the common spring way to access the database, with REST module  added you can call methods using Restful call from any client like JavaScript.


The same POJO which represents the model can easily provide you access to the data using the @Repository.


Spring Data takes this simplification one step forward and makes it possible to remove the DAO implementations entirely – the interface of the DAO is now the only artifact that need to be explicitly defined.


Spring Data amazingly removes the Data access object out of the equation. You just provide the Repository interface and Spring Data does the job perfectly.


The magic of Spring Data can be leveraged by using a small set of Annotations like below,


@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.repositories"})
public class AppConfig{
}

So you repository interface just needs to implement JpaRepository,

and the implementing classes will be found automatically by Spring. These methods can be exposed as webservice by just including the Spring Jars in the class path.