employee database 만들기
1. model 만들기
springserver 안에 model 패키지 만들기, model 패키지 안에 employee 패키지
java class - employee 만들기
Employee.java
package com.genuinecoder.springserver.model.employee;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {
@Id //id가 pk가 됨
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String location;
private String branch;
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 getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
", branch='" + branch + '\'' +
'}';
}
}
왜 import javax 였는데 난 import jakarta이지 ..? 고민하며 구글링 결과
https://post.dooray.io/we-dooray/tech-insight-ko/back-end/4173/
스프링 부트 3.0 으로 전환 - Dooray! POST
2022년 11월에 기존의 Spring framework 5 와 Spring Boot 2.X 버전을 대체하는 Spring framework 6와 Spring Boot 3 가 릴리즈되었습니다. 어떤 변화가 있고, 어떻게 설정해야 할지 알아봅니다
post.dooray.io
나는 스프링부트 3.x 버전이다 ! 기억하기
@GeneratedValue : 기본키 매핑
자동 생성
- IDENTITY : 기본 키 생성을 데이터베이스에 위임, mysql에서 많이 씀
- SEQUENCE : 데이터 베이스 오브젝트 이용. 데이터베이스 시퀀스를 사용해서 기본키 할당, 추가적인 어노테이션으로 @SequenceGenerator 필요, oracle에서 사용
- TABLE : 별도의 키 생성 테이블을 사용, @TableGenerator 필요
- AUTO : 자동으로 기본 값으로 지정
SpringServerApplication.java
package com.genuinecoder.springserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//해당 패키지 모두 스캔
@SpringBootApplication(scanBasePackages = "com.genuinecoder.springserver")
@EnableAutoConfiguration
public class SpringServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringServerApplication.class, args);
}
}
mysql workbench에서 employee table이 추가된 것 확인 가능
2. Setting up DAO (Data Access Object)
EmployeeRepository.java
package com.genuinecoder.springserver.model.employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
//Employee의 pk의 형태인 Integer로 값을 줌
}
EmployeeDao.java
package com.genuinecoder.springserver.model.employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Streamable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class EmployeeDao {
@Autowired
private EmployeeRepository repository;
public void save(Employee employee) {
repository.save(employee);
}
public List<Employee> getAllEmployees() {
List<Employee> employees = new ArrayList<>();
Streamable.of(repository.findAll())
.forEach(employees::add);
return employees;
}
public void delete(Employee employee) {
repository.deleteById(employeeId);
}
}
Data Access Object : all the data will be accessed through this class
3. Test the repository
in order to add a new employee, we need an object of the employee dao
test에서 EmployeeDao 객체 가져오려면 autowiring 필요 !! -> @AutoWired 뭔지 자세히 알아보기
EmployeeDao에서 @Service 해놔서 autowired 가능
SpringServerApplicationTests
package com.genuinecoder.springserver;
import com.genuinecoder.springserver.model.employee.Employee;
import com.genuinecoder.springserver.model.employee.EmployeeDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringServerApplicationTests {
@Autowired
private EmployeeDao employeeDao;
@Test
void addEmployeeTest() {
Employee employee = new Employee();
employee.setName("Rachel");
employee.setLocation("Building-5");
employee.setBranch("IT");
employeeDao.save(employee);
}
}
테스트 코드 돌려보고 결과 확인
여러개 추가해본 결과
getAllEmployees 추가
@SpringBootTest
class SpringServerApplicationTests {
@Autowired
private EmployeeDao employeeDao;
// @Test
// 얘는 test 안시키기 위해서 주석처리
void addEmployeeTest() {
Employee employee = new Employee();
employee.setName("Bruce");
employee.setLocation("Building-X");
employee.setBranch("Security");
employeeDao.save(employee);
}
@Test
void getAllEmployees() {
List<Employee> employees = employeeDao.getAllEmployees();
System.out.println(employees);
}
}
모두 삭제
@Test
void getAllEmployeesAndDeleteThem() {
List<Employee> employees = employeeDao.getAllEmployees();
for (Employee employee : employees) {
employeeDao.delete(employee.getId());
}
}
모두 삭제된것 확인
'BackEnd : Spring > SpringBoot' 카테고리의 다른 글
Android + Spring Boot + Firebase Google Login - FE (1) | 2024.01.25 |
---|---|
Spring Boot Server & Android Client App - Chapter #5, #6 (0) | 2024.01.14 |
Spring Boot Server & Android Client App - Chapter #4 (1) | 2024.01.14 |
Spring Boot Server & Android Client App - Chapter #3 (0) | 2024.01.14 |
Spring Boot Server & Android Client App - Chapter #1 (0) | 2024.01.12 |