SpringBoot Example 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

SpringBoot Example 1

Example 1:

FirstStsProjectApplication.java
package com.cit.FirstSTSProject;

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

@SpringBootApplication
public class FirstStsProjectApplication {

public static void main(String[] args) {


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

FirstController.java
package com.cit.FirstSTSProject.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class FirstController {

@RequestMapping("/test")
@ResponseBody
public String firstHandller() {
return "\n\n...This is Spring Boot using STS...\n\n";
}
}

Example 2:

FirstStsProjectforJspApplication .java

package com.cit.FirstSTSProject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FirstStsProjectforJspApplication {

public static void main(String[] args) {


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

MainController.java
package com.cit.FirstSTSProject.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MainController {

@RequestMapping("/home")
public String view() {
System.out.println("This is home page");
return "home";
}

@RequestMapping("/contact")
public String contact() {
System.out.println("This is contact page");
return "contact";
}
}

application.properties

spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.jsp

contact.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1> This is Contact page</h1>
</body>
</html>

home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1> This is home page</h1>

</body>
</html>

Example 3

User.java

package com.cit.SpringBootJPAExample.entites;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

private String name;

private String city;

private String status;

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getStatus() {


return status;
}

public void setStatus(String status) {


this.status = status;
}

public User(int id, String name, String city, String status) {


super();
this.id = id;
this.name = name;
this.city = city;
this.status = status;
}

public User() {
super();
// TODO Auto-generated constructor stub
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", city=" + city + ", status=" + status
+ "]";
}

UserRepository.java

package com.cit.SpringBootJPAExample.Dao;
import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.cit.SpringBootJPAExample.entites.User;

public interface UserRepository extends CrudRepository<User, Integer>{

//Custom Finder methods


//find - introducer, ByName - criteria using single property
public List<User> findByName(String name);
public List<User> findByCity(String city);
//By Name And City using multiple property
public List<User> findByNameAndCity(String name, String city);

//Executing JPQL Queries


@Query("select u from User u")
public List<User> getAllUser();

//parameterize query
@Query("select u from User u where u.name =:n")
public List<User> getAllUserByName(@Param("n") String name);

//Executing Native Queries


@Query(value = "select * from User", nativeQuery = true)
public List<User> getUserAll();
}

SpringBootJpaExampleApplication.java

package com.cit.SpringBootJPAExample;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;

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

import com.cit.SpringBootJPAExample.Dao.UserRepository;
import com.cit.SpringBootJPAExample.entites.User;

@SpringBootApplication
public class SpringBootJpaExampleApplication {

public static void main(String[] args) {

ApplicationContext context =
SpringApplication.run(SpringBootJpaExampleApplication.class, args);

UserRepository userRepository = context.getBean(UserRepository.class);


// CREATE

// Saving single user

/*
* User user = new User(); user.setName("Shreya"); user.setCity("Kolkata");
* user.setStatus("It is Python"); User userResult = userRepository.save(user);
* System.out.println(userResult);
*/

// Saving multiple objects


// User user1 = new User();
// user1.setName("Shreya");
// user1.setCity("Kolkata");
// user1.setStatus("It is Python");
//
// User user2 = new User();
// user2.setName("Hieu");
// user2.setCity("Ho Chi Minh");
// user2.setStatus("It is Java");
//
// List<User> users = List.of(user1,user2);
// Iterable<User> userResult = userRepository.saveAll(users);
//
// userResult.forEach(user->{
// System.out.println(user);
// });
//

// UPDATE

/*
* Optional<User> optinal = userRepository.findById(10); User user =
* optinal.get();
*
* user.setName("Trang"); user.setCity("Hanoi"); user.setStatus("It is Python");
* User userResult = userRepository.save(user); System.out.println(userResult);
*/

// READ
// findById() - returns optional containing your data

// Iterable<User> itr = userRepository.findAll();

/*
* Iterator<User> iterator = itr.iterator(); while(iterator.hasNext()) { User
* user = iterator.next(); System.out.println(user); }
*/

/*
* itr.forEach(new Consumer<User>() {
*
* @Override public void accept(User t) { System.out.println(t); }
*
* });
*/

// itr.forEach(user->{System.out.println(user);});

// DELETE

// deleting single element


/*
* userRepository.deleteById(10); System.out.println("Data Deleted");
*/

// deleting all elements


/*
* Iterable<User> allusers = userRepository.findAll();
* userRepository.deleteAll(allusers);
*/

//Derived Query Methods / Custom Finder methods


//using single property
/*
* List<User> userName = userRepository.findByName("Shreya");
* userName.forEach(user->System.out.println(user));
*/

//using multiple property


/*
* List<User> userName1 =
userRepository.findByNameAndCity("Shreya","Kolkata");
* userName1.forEach(user->System.out.println(user));
*/

//Executing JPQL Queries


/*
* List<User> allUser = userRepository.getAllUser();
* allUser.forEach(user->System.out.println(user));
*/

//parameterize query
/*
* List<User> allUser = userRepository.getAllUserByName("Shreya");
* allUser.forEach(user->System.out.println(user));
*/

//Executing Native Queries


List<User> allUser1 = userRepository.getUserAll();
allUser1.forEach(user->System.out.println(user));
}

application.properties

spring.datasource.name=test
spring.datasource.url=jdbc:mysql://localhost:3306/debarshi
spring.datasource.username=debarshi
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update

Example 4:

Book.java

package com.cit.SpringBootRestAPIFirst.entities;

public class Book {


private int bookId;
private String title;
private String author;

public Book(int bookId, String title, String author) {


super();
this.bookId = bookId;
this.title = title;
this.author = author;
}

public Book() {
super();
// TODO Auto-generated constructor stub
}

public int getBookId() {


return bookId;
}

public void setBookId(int bookId) {


this.bookId = bookId;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", title=" + title + ", author=" + author + "]";
}
}

BookController.java

package com.cit.SpringBootRestAPIFirst.Contollers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
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.cit.SpringBootRestAPIFirst.Services.BookService;
import com.cit.SpringBootRestAPIFirst.entities.Book;

/*@Controller*/

@RestController
public class BookController {

/* @RequestMapping(value = "/books", method = RequestMethod.GET) */


/* @ResponseBody */
/*
* public String getBooks() { return "This is PostMan Testing"; }
*/

/*
* @GetMapping("/books") public Book getBooks() {
*
* Book book=new Book(); book.setBookId(101);
* book.setTitle("Advance Java Programming");
* book.setAuthor("Debarshi Mazumder");
*
* return book; }
*/

@Autowired
private BookService bookService;

//Get or Read single book handler


@GetMapping("/books")
public List<Book> getBooks() {

return this.bookService.getAllBooks();
}

//Get or Read all book handler


@GetMapping("/books/{id}")
public Book getBook(@PathVariable("id") int id) {

return this.bookService.getBookById(id);
}

//Create new book handler


@PostMapping("/books")
public Book addBook(@RequestBody Book book) {
Book bk = this.bookService.addBook(book);
System.out.println(bk);
return bk;
}

//Delete single book handler


@DeleteMapping("/books/{id}")
public void deleteBook(@PathVariable("id") int id) {

this.bookService.deleteBook(id);
}

//Updating book
@PutMapping("/books/{id}")
public Book updateBook(@RequestBody Book book, @PathVariable("id") int id) {
this.bookService.updateBook(book, id);
System.out.println(book);
return book;
}
}

BookService.java

package com.cit.SpringBootRestAPIFirst.Services;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

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

import com.cit.SpringBootRestAPIFirst.Dao.BookRepository;
import com.cit.SpringBootRestAPIFirst.entities.Book;

@Component
public class BookService {

//@Autowired
//private BookRepository bookRepository;

private static List<Book> list = new ArrayList<>();

static {
list.add(new Book(102, "C++", "Hieu"));
list.add(new Book(103, "C#", "ABC"));
list.add(new Book(104, ".Net", "XYZ"));

public List<Book> getAllBooks() {


//List<Book> list =(List<Book>)this.bookRepository.findAll();
return list;
}

public Book getBookById(int bookId) {


Book book = null;
book = list.stream().filter(e -> e.getBookId() == bookId).findFirst().get();
//this.bookRepository.findById(bookId);
return book;

// Adding or creating the Book


public Book addBook(Book book) {
list.add(book);
//Book book1 = this.bookRepository.save(book);
return book;
}

// Deleting the Book


public void deleteBook(int id) {
list = list.stream().filter(book -> book.getBookId() !=
id).collect(Collectors.toList());

/*
* list = list.stream().filter(book->{ if(book.getBookId()!=id) { return true; }
* else { return false; }
*
* }).collect(Collectors.toList());
*/

//this.bookRepository.deleteById(id);
}

public void updateBook(Book book, int bookId) {

list = list.stream().map(b->{ if(b.getBookId()==bookId) {


b.setTitle(book.getTitle()); b.setAuthor(book.getAuthor()); } return b;
}).collect(Collectors.toList());
//book.setBookId(bookId);
//this.bookRepository.save(book);
}
}

SpringBootRestApiFirstApplication.java

package com.cit.SpringBootRestAPIFirst;

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

@SpringBootApplication
public class SpringBootRestApiFirstApplication {

public static void main(String[] args) {


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

application.properties

spring.datasource.name=test
spring.datasource.url=jdbc:mysql://localhost:3306/debarshi
spring.datasource.username=debarshi
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy