Descripción
Create a Spring Service for CRUD operations on an entity
File Template: ✅
Prefix
spring:service
Scopes
java
Snippet de código
package ${1:com.example.demo.service};
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ${2:com.example.demo.repository.${3:MyRepository}};
import ${4:com.example.demo.model.${5:MyEntity}};
import java.util.List;
import java.util.Optional;
@Service
public class ${6:${5/^(.*)/$1Service/}} {
@Autowired
private ${3:MyRepository} repository;
public List<$5> findAll() {
return repository.findAll();
}
public Optional<$5> findById(Long id) {
return repository.findById(id);
}
public $5 save($5 entity) {
return repository.save(entity);
}
public Optional<$5> update(Long id, $5 entity) {
return repository.findById(id).map(e -> {
entity.setId(id);
return repository.save(entity);
});
}
public boolean delete(Long id) {
if(repository.existsById(id)) {
repository.deleteById(id);
return true;
}
return false;
}
}