Friday, 30 March 2018

how to create Spring Rest Application using Spring boot and spring data jpa

step 1:create the database studentdb
CREATE SCHEMA `studentdb` ;

step 2: create the following table.
CREATE  TABLE `studentdb`.`student` (
  `student_id` BIGINT NOT NULL AUTO_INCREMENT ,
  `student_name` VARCHAR(45) NULL ,
  `student_age` INT NULL ,
  `gender` VARCHAR(6) NULL ,
  PRIMARY KEY (`student_id`) );

Note: for creating table you have to follow the camelCase.
more about you can read from here
http://stackoverflow.com/questions/23456197/spring-data-jpa-repository-underscore-on-entity-column-name and store some data into this tables

INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('ishwar', '26', 'Male');
INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('Yogesh', '24', 'Male');
INSERT INTO `studentdb`.`student` (`student_mame`, `student_age`, `gender`) VALUES ('Mayur', '26', 'Male');
INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('Jaydip', '24', 'Male');
INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('Kirte', '22', 'Male');


step 3: create maven project and gave project name student and give group name students.

step 4:create the com.poolofjava.entities package and create student entities like following.

package com.poolofjava.entities;

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="student")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long studentId;
@Column(name="student_name")
String studentName;
@Column(name="student_age")
int  studentAge;
@Column(name="gender")
String gender;
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student(){
}
/*
* this consturctor is use for the finding student base on the id
* so the id assign using this constructor
*/
public Student(Long studentId){
this.studentId=studentId;
}

}


step 5: now create the repository inside the com.poolofjava.repository package...create class StudentRepository

package com.poolofjava.repository;

import java.util.List;
import org.springframework.data.repository.CrudRepository;

import com.poolofjava.entities.Student;

public interface StudentRepository extends CrudRepository<Student,Long> {
public List<Student> findBystudentId(Long studentId);


}

step 6 :now create the rest controller in the package com.poolofjava.controller

package com.poolofjava.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.poolofjava.entities.Student;
import com.poolofjava.repository.StudentRepository;

@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentRepository student;
@RequestMapping(method = { RequestMethod.GET },value = "/studentid/{studentid}",produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public List<Student> getStudentDeails(@PathVariable("studentid") Long id){
System.out.println("the id is"+id);
return student.findBystudentId(id);
}

}

step 7: now create main application class inside the package com.poolofjava.

package com.poolofjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan
@EnableWebMvc
@EnableSpringDataWebSupport
@EnableTransactionManagement
@EnableJpaRepositories(basePackages={"com.poolofjava.repository"})
@EntityScan(basePackages={"com.poolofjava.entities"})
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) throws Throwable {
       new SpringApplication(Application.class).run(args);
   }

}

step 8: now create the  application.properties file inside the resource folder.

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/studentdb
spring.datasource.username=snefouser
spring.datasource.password=snefouser
spring.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=create-drop

step 9:now modify the pom.xml file

<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>students</groupId>
  <artifactId>student</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>student</name>
  
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>com.poolofjava.Application</start-class>
    <java.version>1.7</java.version>
    <logback.version>1.1.2</logback.version>
    <querydsl.version>3.4.0</querydsl.version>
  </properties>
  
  
  <!-- ths library for the spring data jpa -->
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

<dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-core</artifactId>
        <version>${querydsl.version}</version> 
    </dependency>
    <!-- for executing spring boot suing embeded tomcat -->
     <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
</dependency>
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.30</version>
    </dependency>
    
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version><!--$NO-MVN-MAN-VER$-->
            <configuration>
                <debug>true</debug>
            </configuration>
        </plugin>
    </plugins>
  </build>  
  
</project>

The project structure look will be:





Now run the project using following steps
1)compile the maven project
C:\my_work\student>mvn clean install
2)run the spring boot project using following command or you can run the main application also.
C:\my_work\student>mvn spring-boot:run

now try to search student data using id from browser.

http://localhost:8080/student/studentid/2
output
{"studentId":2,"studentName":"Yogesh","studentAge":24,"gender":"Male"}]