Mega Menu

Monday, April 13, 2020

SpringBoot Spring Data JPA with H2 InMemory DB - Sample Code

1. SpringdatajpaApplication.java 

package com.raj.springdatajpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringdatajpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringdatajpaApplication.class, args);
    }

}


2. Entity class Student.java

package com.raj.springdatajpa.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity

public class Student {

    @Id
    private long id;
    private String name;   
    private int testScore;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getTestScore() {
        return testScore;
    }
    public void setTestScore(int testScore) {
        this.testScore = testScore;
    } 
}


3. Repository Interface

package com.raj.springdatajpa.repos;
import org.springframework.data.jpa.repository.JpaRepository;
import com.raj.springdatajpa.model.Student;

public interface StudentRepository extends JpaRepository {

}


5. JUNIT Test class

package com.raj.springdatajpa;
import static org.junit.Assert.*;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.raj.springdatajpa.model.Student;
import com.raj.springdatajpa.repos.StudentRepository;

@RunWith(SpringRunner.class)
@SpringBootTest

public class SpringdatajpaApplicationTests {
   
    @Autowired
    private StudentRepository stdRepo;
   

    @Test

    public void testSaveStudent() {
        Student student = new Student();
        student.setId(1l);
        student.setName("raj");
        student.setTestScore(100);
        stdRepo.save(student);

        Student savedStudent = stdRepo.findById(1l).get();
        assertEquals(savedStudent.getName(), student.getName());
       
    }
}

 

6. POM.xml
 

No comments:

Post a Comment