관계형 데이터베이스가 지원하는 Spring Boot에서 CRUD Rest 서비스를 구현하는 방법
7464 단어 springrestfulwsjavaspringboot
다음은 개발자가 Spring Boot를 사용하여 간단한 CRUD Rest Service를 구현하기 위해 따라야 하는 주요 단계입니다.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
spring.datasource.url = jdbc:mysql://localhost:3306/<Database_Name>?useSSL=false
spring.datasource.username = <Your User Name>
spring.datasource.password = <Your Password>
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
public User() {
}
public User(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message) {
super(message);
}
}
import java.util.List;
import com.pradz.rest.entity.User;
import com.pradz.rest.exception.ResourceNotFoundException;
import com.pradz.rest.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
// get all users
@GetMapping
public List <User> getAllUsers() {
return this.userRepository.findAll();
}
// get user by id
@GetMapping("/{id}")
public User getUserById(@PathVariable(value = "id") long userId) {
return this.userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id :" + userId));
}
// create user
@PostMapping
public User createUser(@RequestBody User user) {
return this.userRepository.save(user);
}
// update user
@PutMapping("/{id}")
public User updateUser(@RequestBody User user, @PathVariable("id") long userId) {
User existingUser = this.userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id :" + userId));
existingUser.setFirstName(user.getFirstName());
existingUser.setLastName(user.getLastName());
existingUser.setEmail(user.getEmail());
return this.userRepository.save(existingUser);
}
// delete user by id
@DeleteMapping("/{id}")
public ResponseEntity <User> deleteUser(@PathVariable("id") long userId) {
User existingUser = this.userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id :" + userId));
this.userRepository.delete(existingUser);
return ResponseEntity.ok().build();
}
}
[ https://github.com/pradz13/SpringBootCrudRest.git ]
다른 관계형 데이터베이스를 사용하려면 적절한 데이터베이스 드라이버 종속성을 사용하고 그에 따라 application.properties 파일을 업데이트하십시오.
Reference
이 문제에 관하여(관계형 데이터베이스가 지원하는 Spring Boot에서 CRUD Rest 서비스를 구현하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/pradz13/how-to-implement-a-crud-rest-service-in-spring-boot-backed-by-relational-database-5ci1텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)