Directory Structure
add below dependencies
Spring web, datajpa, lombok , h2
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.1.0
com.example
SpringBoot3H2
0.0.1-SNAPSHOT
SpringBoot3H2
Demo project for Spring Boot
17
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
com.h2database
h2
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
Product
package com.example.demo.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Product {
@Id
@GeneratedValue
private Integer prodId;
private String prodName;
private double prodCost;
public Product(String prodName, double prodCost) {
super();
this.prodName = prodName;
this.prodCost = prodCost;
}
}
ProductRepository
package com.example.demo.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.Product;
public interface ProductRepository extends JpaRepository{
}
TestRunner
package com.example.demo.runner;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.example.demo.entity.Product;
import com.example.demo.repo.ProductRepository;
@Component
public class TestRunner implements CommandLineRunner{
@Autowired
private ProductRepository repo;
@Override
public void run(String... args) throws Exception {
Product p1 = new Product("P1",5600.4);
Product p2 = new Product("P2",6600.4);
Product p3 = new Product("P3",7600.4);
//save product
repo.save(p1);
repo.save(p2);
repo.save(p3);
//find
Optional opt = repo.findById(1);
if(opt.isPresent()) {
System.out.println(opt.get());
}else {
System.out.println("Not FOund");
}
//find all
repo.findAll().forEach(System.out::println);
//delete by id
repo.deleteById(1);
//delete all
repo.deleteAll();
}
}