0% found this document useful (0 votes)
7 views12 pages

Spring Boot With Database Connection

Uploaded by

rajaakrajaak82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views12 pages

Spring Boot With Database Connection

Uploaded by

rajaakrajaak82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Spring Boot with Database:

1. Project Structure Overview

Your project follows a standard Spring Boot structure, which typically looks like this:
Add dependency

 Spring web
 Jpa – database oprations
 Mysql

css

Database
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── crud
│ │ │ ├── controllers
│ │ │ │ └── ProductController.java
│ │ │ ├── models
│ │ │ │ └── Product.java
│ │ │ ├── repositories
│ │ │ │ └── ProductRepository.java
│ │ │ ├── services
│ │ │ │ └── ProductService.java
│ │ │ └── DatabaseApplication.java
│ │ └── resources
│ │ └── application.properties
└── pom.xml

2. Application Properties Configuration (application.properties)

This file contains your Spring Boot application's configuration settings, including database
connection details.

Content:

properties

spring.application.name=Database
# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydata
spring.datasource.username=root
spring.datasource.password=root

# Hibernate Configuration
spring.jpa.hibernate.ddl-auto=create-drop

Explanation:

 spring.application.name=Database: Sets the name of the application.


 spring.datasource.url: JDBC URL to connect to the MySQL database.
 spring.datasource.username & spring.datasource.password: Credentials to
connect to the database.
 spring.jpa.hibernate.ddl-auto=create-drop: This setting will drop and recreate
the database schema each time the application is restarted, useful for development
purposes.

Files/Components Needed:

 MySQL Server installed.


 mydata database created in MySQL.

3. Main Application Class (DatabaseApplication.java)

This is the entry point for your Spring Boot application.

Content:

java

package com.crud.Database;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DatabaseApplication {

public static void main(String[] args) {


SpringApplication.run(DatabaseApplication.class, args);
}

Explanation:

 @SpringBootApplication: This annotation is a convenience annotation that adds


@Configuration, @EnableAutoConfiguration, and @ComponentScan.
 main(String[] args): The entry point of the application. It starts the Spring Boot
application.
 @restcontroller -- >@controller – controller file(request handle) @reponsebody—http response
handle

Output:

When you run this application, Spring Boot starts an embedded Tomcat server and deploys the
application.

4. Seeding Data (DataSeeder.java)

This class seeds initial data into the database when the application starts.

Content:

java

package com.crud.Database;

import com.crud.Database.models.Product;
import com.crud.Database.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class DataSeeder implements CommandLineRunner {

@Autowired
private ProductRepository productRepository;

@Override
public void run(String... args) throws Exception {
if (productRepository.count() == 0) {
List<Product> products = Arrays.asList(
new Product("OPPO F21s Pro 5G", 245.67, "OPPO F21s Pro 5G is a
powerful device...", 4.5, "Mobile Phones", "Amazon", 5, 15,
Arrays.asList("https://picsum.photos/200/300",
"https://picsum.photos/200/300")),
new Product("WRISTIO HD, Bluetooth Calling Smart Watch",
150.32, "Minix watches are exclusively...", 3.5, "Accessories", "Flipkart", 9,
5, Arrays.asList("https://picsum.photos/200/300",
"https://picsum.photos/200/300"))
// More products here
);

productRepository.saveAll(products);
System.out.println("Demo data seeded");
}
}
}

Explanation:

 @Component: Marks this class as a Spring component, which will be detected during
component scanning.
 CommandLineRunner: Interface used to run code after the application starts. Extends
CommandLineRunner – its call run method

 productRepository.saveAll(products): Saves the list of products to the database if


the table is empty.

Output:

On application startup, this will seed the database with the specified products.

5. Controller Layer (ProductController.java)

This controller handles HTTP requests related to Product.

Content:

java

package com.crud.Database.controllers;

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

import com.crud.Database.models.Product;
import com.crud.Database.services.ProductService;

import java.util.List;
import java.util.Map;
import java.util.Arrays;

@RestController
@RequestMapping("/products")
public class ProductController {

@Autowired
private ProductService productService;
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}

@GetMapping("/category")
public List<Map<String,Object>> getCategoryProducts() {
return Arrays.asList(
Map.of("name", "Product 1", "price", 234),
Map.of("name", "Product 2", "price", 123)
);
}
}

Explanation:

 Product controller
 Get Allproducts – give the list data
 Arrays. Aslist(map.of(“name”,”product”,”price”,234)
 Get the all data – using @GetMapping(“Products”) -- The data is return List
 But output will show the json data – the reason is ,this work do @RestController inside
@responsebody
 http://localhost:8080/products/ , http://localhost:8080/products/category -- the product url is
common
 so use @RequestMapping(“/products”)

 @RestController: Marks this class as a controller where each method returns a domain
object instead of a view.
 @RequestMapping("/products"): Maps HTTP requests to /products to this controller.
 @GetMapping: Maps GET requests to methods.
 getAllProducts(): Returns all products from the database.

Output:

When you access /products, it returns the list of products.


6. Model Layer (Product.java)

This class represents the Product entity.

Content:

java

package com.crud.Database.models;

import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.util.List;

@Entity
@Table(name ="products")
public class Product {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

private String name;


private double price;
private String description;
private double ratings;
private String category;
private String seller;
private int stock;
private int numOfReviews;

@ElementCollection
@Column(name="image_url")
private List<String> images;
// Constructors, Getters, Setters omitted for brevity
}

Explanation:

 Create Product Entity


 Called models package
 @ID -- Id primarykey
 @GeneratedValue -- generate – auto increament value
 @Entity – identify entity class – model class

 @Entity: Marks this class as a JPA entity.


 @Table(name ="products"): Specifies the table name in the database.
 @Id and @GeneratedValue(strategy=GenerationType.IDENTITY): Marks id as the
primary key and specifies that it will be auto-generated.
 @ElementCollection: Specifies a collection of basic types.

Output:

This class will map to the products table in the database.

7. Repository Layer (ProductRepository.java)

This interface interacts with the database.

Content:

java

package com.crud.Database.repositories;

import com.crud.Database.models.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}

Explanation:

 Creating Product Service and Repository


 Creating Product Repository:

 Create interface – Database access – repository package


 @Repository – identify repository interface
 Extends JpaRepository – generic type – for product repository – id double so give long

 @Repository: Marks this interface as a repository.


 JpaRepository<Product, Long>: Provides CRUD operations for Product.

Output:

You can use this repository to interact with the Product table in the database.

8. Service Layer (ProductService.java)

This class contains the business logic.

Content:

java

package com.crud.Database.services;

import com.crud.Database.models.Product;
import com.crud.Database.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class ProductService {

@Autowired
private ProductRepository productRepository;

public List<Product> getAllProducts() {


return productRepository.findAll();
}
}

Explanation:

 Creating Product Service:


 Create class – business logic – services package
 @Service – identify service class
 Add product repository – create product repository create object using @Autowired – method
dependency injection

Create getallproducts():
Return the product list – using findAll() method

 @Service: Marks this class as a service component.


 getAllProducts(): Returns all products from the database using the
ProductRepository.

Output:

This service method can be used in the controller to fetch data from the database.

9. Running the Application

Steps:

1. Ensure that MySQL is installed and running on your local machine.


2. Create a database named mydata in MySQL.
3. Set up the database connection details in application.properties.
4. Run the Spring Boot application (DatabaseApplication.java).
5. Access http://localhost:8080/products to see the list of products.

10. What You Need to Execute This Project:

 MySQL Database: Ensure MySQL is installed and running.


 IDE: IntelliJ IDEA or Eclipse for running the Spring Boot project.
 JDK: Java Development Kit (JDK 17).
 Maven: To manage dependencies (POM file is used here).

You might also like