본문 바로가기

스프링부트(Spring Boot)

Staff 생성 및 CRUD작업 (smsapi 프로젝트)

1. StaffEntity 클래스 생성

public class StaffEntity {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public long id;
	
	@Column(nullable = false, unique = true)
	public String username;
	
	@Column(nullable = false)
	public String password;
	
	public Date createDate;
	
	public Date updateDate;
	
}

2. StaffDTO 클래스 생성

public class StaffDTO {
	public long id;
	public String username;
	public String password;
	public String password2;
	public String orgPassword; // 새로 추가된 column
	public Date createDate;
	public Date updateDate;
}

3. StaffRepository 인터페이스 생성

public interface StaffRepository extends JpaRepository<StaffEntity, Long>{

}

4. StaffController 클래스 생성

@RestController
@RequestMapping("/staff")
public class StaffController {

	@Autowired
	private StaffService staffService;
    
}

5. StaffService 클래스 생성

@Service
public class StaffService {
	
	@Autowired
	private StaffRepository staffRepository;
    
}

 

6. 특정 username으로 그 staff 의 데이터 가져오기

@RestController
@RequestMapping("/staff")
public class StaffController {

	@GetMapping("/name/{username}")
	public ResponseEntity<?> findByUsername(@PathVariable("username") String username){
    	Map<String, Object> map = new HashMap<>();
        
		if(username==null || username.equals("")) {
			return ResponseEntity.badRequest().body("이름이 없습니다.");
		}
		
		try {
			StaffDTO dto = staffService.findByUsername(username);
			map.put("dto", dto);
			return ResponseEntity.ok().body(map);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err", "실패"); 
			return ResponseEntity.badRequest().body(map);
		}
	}
}
@Service
public class StaffService {
	
	public StaffDTO findByUsername(String username) {
		
		StaffEntity entity = staffRepository.findByUsername(username);
	
		if(entity == null) {
			throw new RuntimeException("해당 이름은 존재하지 않습니다.");
		}
        
		return new ModelMapper().map(entity, StaffDTO.class);
	}
}

 

7. 모든 staff 데이터 가져오기

@RestController
@RequestMapping("/staff")
public class StaffController {

    @GetMapping("/all")
	public ResponseEntity<?> findAll(){
		Map<String, Object> map = new HashMap<>();
		
		try {
			List<StaffDTO> list = staffService.findAll();
			map.put("list", list);
			return ResponseEntity.ok().body(map);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err", "에러 발생");
			return ResponseEntity.badRequest().body(map);
		}
	}
}
@Service
public class StaffService {

    public List<StaffDTO> findAll() {
		
		List<StaffEntity> list_entity = staffRepository.findAll();
		
		List<StaffDTO> list_dto = new ArrayList<>();
		
		for(StaffEntity e : list_entity) {
			list_dto.add(new ModelMapper().map(e, StaffDTO.class));
		}
		
//		list_entity.forEach(e -> list_dto.add(new ModelMapper().map(e, StaffDTO.class)) );
//		위의 for문의 코드와 똑같음.
		
		return list_dto;
	}
}

 

8. insert 작업

@RestController
@RequestMapping("/staff")
public class StaffController {

    @PostMapping("")
	public ResponseEntity<?> save(@RequestBody StaffDTO staffDTO){
		if(staffDTO == null) {
			return ResponseEntity.badRequest().body("입력 정보에 문제가 있습니다.");
		}
		if(staffDTO.getId() !=0) {
			return ResponseEntity.badRequest().body("입력 정보에 문제가 있습니다.");
		}
		if(staffDTO.getPassword() == null) {
			return ResponseEntity.badRequest().body("입력 정보에 문제가 있습니다.");
		}
		if(staffDTO.getPassword2() == null) {
			return ResponseEntity.badRequest().body("입력 정보에 문제가 있습니다.");
		}
		if(!staffDTO.getPassword().equals(staffDTO.getPassword2())) {
			return ResponseEntity.badRequest().body("비밀번호가 일치하지 않습니다.");
		}
        
		Map<String, Object> map = new HashMap<>();
		
		try {
			staffDTO = staffService.save(staffDTO);
			map.put("dto", staffDTO);
			return ResponseEntity.ok().body(map);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err", "입력 실패했습니다.");
			return ResponseEntity.badRequest().body(map);
		}
	}
}
@Service
public class StaffService {

    public StaffDTO save(StaffDTO staffDTO) {
		
		StaffEntity staffEntity = new ModelMapper().map(staffDTO, StaffEntity.class);
		
		Date date = new Date();
		staffEntity.setCreateDate(date);
		staffEntity.setUpdateDate(date);
				
		staffEntity = staffRepository.save(staffEntity);
		
		return new ModelMapper().map(staffEntity, StaffDTO.class);
	}
}

 

9. update 작업

@RestController
@RequestMapping("/staff")
public class StaffController {

    @PutMapping("")
	public ResponseEntity<?> update(@RequestBody StaffDTO staffDTO){
		Map<String, Object> map = new HashMap<>();
		String password = staffDTO.getPassword();
		String password2 = staffDTO.getPassword2();
        StaffDTO db_staffDTO = staffService.findByUsernameAndPassword(staffDTO.getUsername(), staffDTO.getOrgPassword());
        
		if(staffDTO == null) {
			return ResponseEntity.badRequest().body("something wrong1");
		}
		if(staffDTO.getOrgPassword() == null) {
			return ResponseEntity.badRequest().body("something wrong2");
		}
		if(staffDTO.getUsername() == null) {
			return ResponseEntity.badRequest().body("something wrong3");
		}
		if(password == null) {
			return ResponseEntity.badRequest().body("something wrong4");
		}
		if(password2 == null) {
			return ResponseEntity.badRequest().body("something wrong5");
		}
		if(!password.equals(password2)) {
			return ResponseEntity.badRequest().body("something wrong6");
		}
		
		if(db_staffDTO == null) {
			return ResponseEntity.badRequest().body("something wrong7");
		}
		
		db_staffDTO.setPassword(password); // 새로운 비밀번호 설정
		
		try {
			staffDTO = staffService.update(db_staffDTO);
			map.put("dto", staffDTO);
			return ResponseEntity.ok().body(map);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err", "수정 실패");
			return ResponseEntity.ok().body(map);
		}
	}
}
@Service
public class StaffService {

	public StaffDTO findByUsernameAndPassword(String username, String orgPassword) {
		
		StaffEntity entity = staffRepository.findByUsernameAndPassword(username, orgPassword);
		
		return new ModelMapper().map(entity, StaffDTO.class);
	}

	@Transactional
	public StaffDTO update(StaffDTO staffDTO) {
    
		StaffEntity entity = new ModelMapper().map(staffDTO, StaffEntity.class);
		
		entity.setUpdateDate(new Date()); // 수정 시각 설정
		
		entity = staffRepository.save(entity);
		
		return new ModelMapper().map(entity, StaffDTO.class);
	}
}

 

10. delete 작업

@RestController
@RequestMapping("/staff")
public class StaffController {
	
	@DeleteMapping("")
	public ResponseEntity<?> delete(@RequestBody StaffDTO staffDTO){
		Map<String, Object> map = new HashMap<>();
	      
	    if(staffDTO.getUsername() != null || !staffDTO.getUsername().equals("") 
        || staffDTO.getPassword() != null || !staffDTO.getPassword().equals("")) {
	      	try {
	            staffService.delete(staffDTO);
	            map.put("result", "삭제 성공");
	            return ResponseEntity.ok().body(map);
	         } catch (Exception e) {
	            e.printStackTrace();
	            map.put("result", "삭제실패");
	            return ResponseEntity.badRequest().body(map);
	         }
	         
	      }else {
	         return ResponseEntity.badRequest().body("해당 데이터는 없습니다");
	      }
	   }
}
@Service
public class StaffService {	

    @Transactional
	public void delete(StaffDTO staffDTO) {
    
		StaffEntity entity =
				staffRepository.findByUsernameAndPassword(staffDTO.getUsername(), staffDTO.getPassword());
	      
		if(entity == null) {
			throw new RuntimeException("해당 스탭은 없습니다.");
		}
	      
		staffRepository.delete(entity);
	}
}