봄 JPA DAO
예를 들어 엔터티 그룹이 있습니다.
이 엔티티에 대해 저장소 GroupRepository를 작성합니다.
public interface GroupRepository extends JpaRepository<Group, Long> {
}
그런 다음이 리포지토리를 사용할 서비스 계층을 만들어야합니다.
public interface Service<T, ID> {
T save(T entity);
void deleteById(ID id);
List<T> findAll();
T getOne(ID id);
T editEntity(T entity);
Optional<T> findById(ID id);
}
public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {
private final R repository;
protected AbstractService(R repository) {
this.repository = repository;
}
@Override
public T save(T entity) {
return repository.save(entity);
}
@Override
public void deleteById(ID id) {
repository.deleteById(id);
}
@Override
public List<T> findAll() {
return repository.findAll();
}
@Override
public T getOne(ID id) {
return repository.getOne(id);
}
@Override
public Optional<T> findById(ID id) {
return repository.findById(id);
}
@Override
public T editEntity(T entity) {
return repository.saveAndFlush(entity);
}
}
@org.springframework.stereotype.Service
public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {
private final GroupRepository groupRepository;
@Autowired
protected GroupServiceImpl(GroupRepository repository) {
super(repository);
this.groupRepository = repository;
}
}
그리고 컨트롤러에서 우리는이 서비스를 사용합니다.
@RestController
@RequestMapping("/api")
class GroupController {
private final Logger log = LoggerFactory.getLogger(GroupController.class);
private final GroupServiceImpl groupService;
@Autowired
public GroupController(GroupServiceImpl groupService) {
this.groupService = groupService;
}
@GetMapping("/groups")
Collection<Group> groups() {
return groupService.findAll();
}
@GetMapping("/group/{id}")
ResponseEntity<?> getGroup(@PathVariable Long id) {
Optional<Group> group = groupService.findById(id);
return group.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping("/group")
ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {
log.info("Request to create group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.created(new URI("/api/group/" + result.getId()))
.body(result);
}
@PutMapping("/group")
ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {
log.info("Request to update group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.ok().body(result);
}
@DeleteMapping("/group/{id}")
public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
log.info("Request to delete group: {}", id);
groupService.deleteById(id);
return ResponseEntity.ok().build();
}
}