├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── companyname │ │ └── springbootcrudrest │ │ ├── SpringBootCrudRestApplication.java │ │ ├── controller │ │ └── UserController.java │ │ ├── exception │ │ ├── ErrorDetails.java │ │ ├── GlobalExceptionHandler.java │ │ └── ResourceNotFoundException.java │ │ ├── model │ │ └── User.java │ │ └── repository │ │ └── UserRepository.java └── resources │ └── application.properties └── test └── java └── com └── companyname └── projectname └── springbootcrudrest └── SpringBootCrudRestApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | # springboot-jpa-crud-rest 2 | CRUD Rest APIs using Spring boot 2, JPA, Hibernate 2 and MySQL 3 | 4 | http://www.javaguides.net/2018/09/spring-boot-2-hibernate-5-mysql-crud-rest-api-tutorial.html 5 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.companyname 7 | springbootcrudrest 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | springbootcrudrest 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 3.0.4 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 17 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-devtools 43 | runtime 44 | 45 | 46 | com.mysql 47 | mysql-connector-j 48 | runtime 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-test 53 | test 54 | 55 | 56 | 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-maven-plugin 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /src/main/java/com/companyname/springbootcrudrest/SpringBootCrudRestApplication.java: -------------------------------------------------------------------------------- 1 | package com.companyname.springbootcrudrest; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 6 | 7 | @SpringBootApplication 8 | @EnableJpaAuditing 9 | public class SpringBootCrudRestApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringBootCrudRestApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/companyname/springbootcrudrest/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.companyname.springbootcrudrest.controller; 2 | 3 | import java.util.Date; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import jakarta.validation.Valid; 9 | 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.web.bind.annotation.DeleteMapping; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.PathVariable; 15 | import org.springframework.web.bind.annotation.PostMapping; 16 | import org.springframework.web.bind.annotation.PutMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | import com.companyname.springbootcrudrest.exception.ResourceNotFoundException; 22 | import com.companyname.springbootcrudrest.model.User; 23 | import com.companyname.springbootcrudrest.repository.UserRepository; 24 | 25 | @RestController 26 | @RequestMapping("/api/v1") 27 | public class UserController { 28 | 29 | @Autowired 30 | private UserRepository userRepository; 31 | 32 | 33 | @GetMapping("/users") 34 | public List getAllUsers() { 35 | return userRepository.findAll(); 36 | } 37 | 38 | @GetMapping("/users/{id}") 39 | public ResponseEntity getUserById( 40 | @PathVariable(value = "id") Long userId) throws ResourceNotFoundException { 41 | User user = userRepository.findById(userId) 42 | .orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId)); 43 | return ResponseEntity.ok().body(user); 44 | } 45 | 46 | @PostMapping("/users") 47 | public User createUser(@Valid @RequestBody User user) { 48 | return userRepository.save(user); 49 | } 50 | 51 | @PutMapping("/users/{id}") 52 | public ResponseEntity updateUser( 53 | @PathVariable(value = "id") Long userId, 54 | @Valid @RequestBody User userDetails) throws ResourceNotFoundException { 55 | User user = userRepository.findById(userId) 56 | .orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId)); 57 | 58 | user.setEmailId(userDetails.getEmailId()); 59 | user.setLastName(userDetails.getLastName()); 60 | user.setFirstName(userDetails.getFirstName()); 61 | user.setUpdatedAt(new Date()); 62 | final User updatedUser = userRepository.save(user); 63 | return ResponseEntity.ok(updatedUser); 64 | } 65 | 66 | @DeleteMapping("/users/{id}") 67 | public Map deleteUser( 68 | @PathVariable(value = "id") Long userId) throws ResourceNotFoundException { 69 | User user = userRepository.findById(userId) 70 | .orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId)); 71 | 72 | userRepository.delete(user); 73 | Map response = new HashMap<>(); 74 | response.put("deleted", Boolean.TRUE); 75 | return response; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/companyname/springbootcrudrest/exception/ErrorDetails.java: -------------------------------------------------------------------------------- 1 | package com.companyname.springbootcrudrest.exception; 2 | 3 | import java.util.Date; 4 | 5 | public class ErrorDetails { 6 | private Date timestamp; 7 | private String message; 8 | private String details; 9 | 10 | public ErrorDetails(Date timestamp, String message, String details) { 11 | super(); 12 | this.timestamp = timestamp; 13 | this.message = message; 14 | this.details = details; 15 | } 16 | 17 | public Date getTimestamp() { 18 | return timestamp; 19 | } 20 | 21 | public String getMessage() { 22 | return message; 23 | } 24 | 25 | public String getDetails() { 26 | return details; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/companyname/springbootcrudrest/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.companyname.springbootcrudrest.exception; 2 | 3 | import java.util.Date; 4 | 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.ControllerAdvice; 8 | import org.springframework.web.bind.annotation.ExceptionHandler; 9 | import org.springframework.web.context.request.WebRequest; 10 | 11 | @ControllerAdvice 12 | public class GlobalExceptionHandler { 13 | @ExceptionHandler(ResourceNotFoundException.class) 14 | public ResponseEntity resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) { 15 | ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); 16 | return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); 17 | } 18 | 19 | @ExceptionHandler(Exception.class) 20 | public ResponseEntity globleExcpetionHandler(Exception ex, WebRequest request) { 21 | ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); 22 | return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/companyname/springbootcrudrest/exception/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.companyname.springbootcrudrest.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(value = HttpStatus.NOT_FOUND) 7 | public class ResourceNotFoundException extends Exception{ 8 | 9 | private static final long serialVersionUID = 1L; 10 | 11 | public ResourceNotFoundException(String message){ 12 | super(message); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/companyname/springbootcrudrest/model/User.java: -------------------------------------------------------------------------------- 1 | package com.companyname.springbootcrudrest.model; 2 | 3 | import java.util.Date; 4 | 5 | import jakarta.persistence.*; 6 | 7 | import org.springframework.data.annotation.CreatedBy; 8 | import org.springframework.data.annotation.CreatedDate; 9 | import org.springframework.data.annotation.LastModifiedBy; 10 | import org.springframework.data.annotation.LastModifiedDate; 11 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 12 | 13 | @Entity 14 | @Table(name = "users") 15 | @EntityListeners(AuditingEntityListener.class) 16 | public class User { 17 | 18 | private long id; 19 | private String firstName; 20 | private String lastName; 21 | private String emailId; 22 | private Date createdAt; 23 | private String createdBy; 24 | private Date updatedAt; 25 | private String updatedby; 26 | 27 | @Id 28 | @GeneratedValue(strategy = GenerationType.AUTO) 29 | public long getId() { 30 | return id; 31 | } 32 | public void setId(long id) { 33 | this.id = id; 34 | } 35 | 36 | @Column(name = "first_name", nullable = false) 37 | public String getFirstName() { 38 | return firstName; 39 | } 40 | public void setFirstName(String firstName) { 41 | this.firstName = firstName; 42 | } 43 | 44 | @Column(name = "last_name", nullable = false) 45 | public String getLastName() { 46 | return lastName; 47 | } 48 | public void setLastName(String lastName) { 49 | this.lastName = lastName; 50 | } 51 | 52 | @Column(name = "email_address", nullable = false) 53 | public String getEmailId() { 54 | return emailId; 55 | } 56 | public void setEmailId(String emailId) { 57 | this.emailId = emailId; 58 | } 59 | 60 | @Column(name = "created_at", nullable = false) 61 | @CreatedDate 62 | @Temporal(TemporalType.TIMESTAMP) 63 | public Date getCreatedAt() { 64 | return createdAt; 65 | } 66 | public void setCreatedAt(Date createdAt) { 67 | this.createdAt = createdAt; 68 | } 69 | 70 | @Column(name = "created_by", nullable = false) 71 | @CreatedBy 72 | public String getCreatedBy() { 73 | return createdBy; 74 | } 75 | public void setCreatedBy(String createdBy) { 76 | this.createdBy = createdBy; 77 | } 78 | 79 | @Column(name = "updated_at", nullable = false) 80 | @LastModifiedDate 81 | @Temporal(TemporalType.TIMESTAMP) 82 | public Date getUpdatedAt() { 83 | return updatedAt; 84 | } 85 | public void setUpdatedAt(Date updatedAt) { 86 | this.updatedAt = updatedAt; 87 | } 88 | 89 | @Column(name = "updated_by", nullable = false) 90 | @LastModifiedBy 91 | public String getUpdatedby() { 92 | return updatedby; 93 | } 94 | public void setUpdatedby(String updatedby) { 95 | this.updatedby = updatedby; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/companyname/springbootcrudrest/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.companyname.springbootcrudrest.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.companyname.springbootcrudrest.model.User; 7 | 8 | @Repository 9 | public interface UserRepository extends JpaRepository{ 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | ## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false 3 | spring.datasource.username = root 4 | spring.datasource.password = root 5 | 6 | 7 | ## Hibernate Properties 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update 13 | 14 | # Below property is to configure context path for spring boot app. 15 | # If you don't want context path then comment below property 16 | server.servlet.context-path=/springboot-crud-rest 17 | -------------------------------------------------------------------------------- /src/test/java/com/companyname/projectname/springbootcrudrest/SpringBootCrudRestApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.companyname.projectname.springbootcrudrest; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.web.client.TestRestTemplate; 11 | import org.springframework.boot.web.server.LocalServerPort; 12 | import org.springframework.http.HttpEntity; 13 | import org.springframework.http.HttpHeaders; 14 | import org.springframework.http.HttpMethod; 15 | import org.springframework.http.HttpStatus; 16 | import org.springframework.http.ResponseEntity; 17 | import org.springframework.test.context.junit4.SpringRunner; 18 | import org.springframework.web.client.HttpClientErrorException; 19 | 20 | import com.companyname.springbootcrudrest.SpringBootCrudRestApplication; 21 | import com.companyname.springbootcrudrest.model.User; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(classes = SpringBootCrudRestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class SpringBootCrudRestApplicationTests { 26 | 27 | @Autowired 28 | private TestRestTemplate restTemplate; 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | private String getRootUrl() { 34 | return "http://localhost:" + port; 35 | } 36 | 37 | @Test 38 | public void contextLoads() { 39 | 40 | } 41 | 42 | @Test 43 | public void testGetAllUsers() { 44 | HttpHeaders headers = new HttpHeaders(); 45 | HttpEntity entity = new HttpEntity(null, headers); 46 | 47 | ResponseEntity response = restTemplate.exchange(getRootUrl() + "/users", 48 | HttpMethod.GET, entity, String.class); 49 | 50 | assertNotNull(response.getBody()); 51 | } 52 | 53 | @Test 54 | public void testGetUserById() { 55 | User user = restTemplate.getForObject(getRootUrl() + "/users/1", User.class); 56 | System.out.println(user.getFirstName()); 57 | assertNotNull(user); 58 | } 59 | 60 | @Test 61 | public void testCreateUser() { 62 | User user = new User(); 63 | user.setEmailId("admin@gmail.com"); 64 | user.setFirstName("admin"); 65 | user.setLastName("admin"); 66 | user.setCreatedBy("admin"); 67 | user.setUpdatedby("admin"); 68 | 69 | ResponseEntity postResponse = restTemplate.postForEntity(getRootUrl() + "/users", user, User.class); 70 | assertNotNull(postResponse); 71 | assertNotNull(postResponse.getBody()); 72 | } 73 | 74 | @Test 75 | public void testUpdatePost() { 76 | int id = 1; 77 | User user = restTemplate.getForObject(getRootUrl() + "/users/" + id, User.class); 78 | user.setFirstName("admin1"); 79 | user.setLastName("admin2"); 80 | 81 | restTemplate.put(getRootUrl() + "/users/" + id, user); 82 | 83 | User updatedUser = restTemplate.getForObject(getRootUrl() + "/users/" + id, User.class); 84 | assertNotNull(updatedUser); 85 | } 86 | 87 | @Test 88 | public void testDeletePost() { 89 | int id = 2; 90 | User user = restTemplate.getForObject(getRootUrl() + "/users/" + id, User.class); 91 | assertNotNull(user); 92 | 93 | restTemplate.delete(getRootUrl() + "/users/" + id); 94 | 95 | try { 96 | user = restTemplate.getForObject(getRootUrl() + "/users/" + id, User.class); 97 | } catch (final HttpClientErrorException e) { 98 | assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND); 99 | } 100 | } 101 | 102 | } 103 | --------------------------------------------------------------------------------