Spring Data JPA example using spring boot

In this example, we will see Spring Data JPA example using spring boot. We will create a maven project from the beginning and implement Spring data using spring boot.

prerequisites –

  • JDK 1.8
  • Oracle 10g
  • Eclipse
  • maven
  • postman

We will use the spring boot library (will provide dependency in pom.xml) to make sure all necessary jar/library is easily available for our application. Spring boot will take care of all jar. Let’ s start.

Spring Data JPA example using spring boot.

Create a maven project.

Modify the pom.xml with below code.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>springdataexample</groupId>
  <artifactId>springdataexample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springdataexample</name>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
 </parent>
  <dependencies>
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency> -->
        
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
        </dependency>
   </dependencies>
   
   
   
   
   
   <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <start-class>com.springdata.springdataexample.SpringDataExampleUsingOracle</start-class>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.springdata.springdataexample.SpringDataExampleUsingOracle</mainClass>
                </configuration>
            </plugin>
			<plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <fork>true</fork>
                <executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
            </configuration>
        </plugin>
        </plugins>
    </build>
   
    
   
 </project>

 

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

 

Let maven download all necessary jar. Once it is done we will able to see maven dependency folder which contains different jar files.

 

We can start to write our controller classes, ServiceImpl and Repository. The folder structure of application-

Spring Data JPA example using spring boot

 

Define main class SpringDataExampleUsingOracle.java


SpringDataExampleUsingOracle.java

package com.springdata.springdataexample;

import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;





@SpringBootApplication(scanBasePackages={"com.springdata"})
@EntityScan("com.springdata.*") 
public class SpringDataExampleUsingOracle {
	
	
	public static void main(final String[] args) {
		final ConfigurableApplicationContext configurableApplicationContext = SpringApplication
				.run(SpringDataExampleUsingOracle.class, args);
		
		
	}
	
	@Bean
	public SessionFactory sessionFactory(final HibernateEntityManagerFactory hemf) {
		return hemf.getSessionFactory();
	}
	

	
	
	
	
}

 

Define entity class i.e Book.java

Book.java

package com.springdata.entity;

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 = "book")
public class Book {
	 
	 @Id
	 @GeneratedValue(strategy = GenerationType.AUTO)
	 private int bookId;
	 
	 @Column(name="book_name")
	 private String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	
	 
	 
}

Define repository interface extending CrudRepository.

BookRepository.java

package com.springdata.repository;


import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;

import org.springframework.stereotype.Repository;

import com.springdata.entity.Book;

@Repository
public interface BookRepository extends CrudRepository<Book,Serializable> {
	public Book findByBookId(int bookId);
}


 

Define service interface i.e BookService.java

BookService.java

package com.springdata.service;

import org.springframework.stereotype.Component;

import com.springdata.entity.Book;
@Component
public interface BookService {
	public Book findByBookId(int bookId);
}

Define service impl class.

BookServiceImpl.java


package com.springdata.serviceimpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.springdata.entity.Book;
import com.springdata.repository.BookRepository;
import com.springdata.service.BookService;
@Service("bookServiceImpl")
public class BookServiceImpl implements BookService{
	
@Autowired
private BookRepository bookRepository;
@Override
public Book findByBookId(int bookId) {
	Book book = bookRepository.findByBookId(bookId);
	return book;
}

}

 

Define controller class.

BookController.java

package com.springdata.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.springdata.entity.Book;
import com.springdata.service.BookService;

@RestController
@RequestMapping("/book")
public class BookController {
	@Autowired
	private BookService bookService;
	
	@RequestMapping(value = "/getBook",method = RequestMethod.GET)
    @ResponseBody
    public Book getPassengerDetails(int bookId) {
		Book bookResponse = bookService.findByBookId(bookId);
		
		return bookResponse;
	}
}

 

Define JpaConfig class.


JpaConfig.java

package com.springdata.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableJpaRepositories(basePackages = "com.springdata.repository")

public class JpaConfig {

}

 

Define application.properties file

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true


spring.jpa.hibernate.ddl-auto =update




spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect

server.port = 9091

  useBuiltinConverters: true
 
  #useAutoMapping: true
  
  
  mapNulls: true


logging.level.org.springframework.transaction.interceptor=TRACE

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

 

 

We are almost done. Since we are using oracle as a database we need to use ojdbc14.jar. I tried to add the dependency in pom.xml but getting some problem, so we added it explicitly.

right click on application/properties/java build path/libraries/add external jar/add  ojdbc14.jar

Run the SpringDataExampleUsingOracle.java as java application. Our application will deploy and book table should created.

 

We can see tomcat started as in above screen.

Verify book table is created or not. If the book table is there just insert dummy record and later we will pass from postman and retrieve the record using Spring data.

Spring Data JPA example using spring boot

 

Open postman and perform get operation. We are performing only get operation here to keep this article simple. We will have a separate article where we will perform CRUD operation.

 

Spring Data JPA example using spring boot

 

That’s all about Spring Data JPA example using spring boot.

You may like.

Spring Data JPA docs see here.