相关疑难解决方法(0)

将Iterable转换为Collection的简便方法

在我的应用程序中,我使用第三方库(确切地说是MongoDB的Spring Data).

这个库的方法返回Iterable<T>,而我的其余代码需要Collection<T>.

有什么实用方法可以让我快速将一个转换为另一个吗?我想避免foreach在我的代码中为这么简单的事情创建一堆循环.

java collections

398
推荐指数
15
解决办法
31万
查看次数

如何在 CrudRepository 上使用 findAll() 返回一个 List 而不是 Iterable

我想编写一个 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)

学生资料库 …

java spring spring-mvc spring-boot

3
推荐指数
4
解决办法
3万
查看次数

Spring Boot REST API 给出空行

我是 Spring Boot 的新手。我有一个带有数据的 MYSQL 表“客户”,如下所示: 表中的数据使用 Postman 测试 API 输出时,似乎有几行空的 JSON 输出。

API 输出

下面是我的代码:

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)

java rest spring-boot

1
推荐指数
1
解决办法
1161
查看次数

标签 统计

java ×3

spring-boot ×2

collections ×1

rest ×1

spring ×1

spring-mvc ×1