在我的应用程序中,我使用第三方库(确切地说是MongoDB的Spring Data).
这个库的方法返回Iterable<T>,而我的其余代码需要Collection<T>.
有什么实用方法可以让我快速将一个转换为另一个吗?我想避免foreach在我的代码中为这么简单的事情创建一堆循环.
我想编写一个 FindAll() 方法,该方法返回所有 Student 对象的列表。但是 CRUDRepository 只有 Iterable<> findAll()。
目标是将所有学生放在一个列表中并将其传递给 API 控制器,以便我可以通过 http GET 获取所有学生。
将此方法转换为 List<> FindAll() 的最佳方法是什么
在我当前的代码中,StudentService 中的 findAll 方法给了我找到的不兼容类型:Iterable。必需:列表错误。
服务
@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {
@Autowired
private final StudentRepository studentRepository;
//Incompatible types found: Iterable. Required: List
public List<Student> findAll() {
return studentRepository.findAll();
}
}
Run Code Online (Sandbox Code Playgroud)
API控制器
@RestController
@RequestMapping("/api/v1/students")
public class StudentAPIController {
private final StudentRepository studentRepository;
public StudentAPIController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping
public ResponseEntity<List<Student>> findAll() {
return ResponseEntity.ok(StudentServiceImpl.findAll());
}
}
Run Code Online (Sandbox Code Playgroud)
学生资料库 …
我是 Spring Boot 的新手。我有一个带有数据的 MYSQL 表“客户”,如下所示: 表中的数据使用 Postman 测试 API 输出时,似乎有几行空的 JSON 输出。
下面是我的代码:
package com.semika.customer;
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="customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="address")
private String address;
public Customer() {
super();
}
}
Run Code Online (Sandbox Code Playgroud)
客户资料库
package com.semika.customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Long>{
}
Run Code Online (Sandbox Code Playgroud)
客户服务
package com.semika.customer;
public interface CustomerService …Run Code Online (Sandbox Code Playgroud)