使用Spring Boot从数据库中检索列表

时间:2018-10-26 15:58:39

标签: java spring-mvc spring-boot spring-repositories

我有一个名为findall_db的数据库,其中有一个名为person的表...我已向该表中手动添加了一些值,并希望使用Spring Boot检索它们。这就是我所拥有的,但是我的控制器中不断出现此错误:Type mismatch: cannot convert from Iterable<PersonInfo> to List<PersonInfo>

实体类为:

@Entity
@Table(name = "Person")
public class PersonInfo implements Serializable {

    private static final long serialVersionUID = 1 L;

    @Id
    @SequenceGenerator(name = "PERSON_GENERATOR", sequenceName = "PERSON_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PERSON_GENERATOR")
    private Long id;

    @Column(name = "ssn")
    private String socialSecurityNumber;

    private String name;

    public PersonInfo() {}

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSocialSecurityNumber() {
        return socialSecurityNumber;
    }

    public void setSocialSecurityNumber(String socialSecurityNumber) {
        this.socialSecurityNumber = socialSecurityNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "PersonInfo [id=" + id + ", socialSecurityNumber=" + socialSecurityNumber + ", name=" + name + "]";
    }

}

存储库类为:

@Repository
public interface PersonInfoRepository extends CrudRepository < PersonInfo, Long > {

 }

控制器为:

@Controller
public class PersonController {

    @Autowired
    PersonInfoRepository personRepo;

    @ResponseBody
    @GetMapping("/people")
    public List printPersonInfo() {

        List < PersonInfo > people = personRepo.findAll();

        System.out.println(people.toString());

        return people;
    }
}

4 个答案:

答案 0 :(得分:1)

这是因为CrudRepository#findAll返回Iterable而不是List。因此,您要么(1)更改方法签名以也返回Iterable,要么您(2)将元素复制到List并退回。

(1)返回Iterable

public Iterable<PersonInfo> printPersonInfo() {
    return personRepo.findAll();
}

(2)将元素复制到List并返回列表。

public List<PersonInfo> printPersonInfo() {
    List<PersonInfo> list = new ArrayList<>();
    personRepo.findAll().forEach(list::add);
    return list;
}

答案 1 :(得分:0)

使您的存储库扩展JpaRepository而不是CrudRepository

@Repository
public interface PersonInfoRepository extends JpaRepository < PersonInfo, Long > {

 }

答案 2 :(得分:0)

@Autowired
PersonInfoRepository personRepo;

@ResponseBody
@GetMapping("/people")
public List printPersonInfo() {

    List < PersonInfo > people = personRepo.findAll();

    System.out.println(people.toString());

    return people;
}

在这部分代码中,您没有初始化(最好广播)控制器变量

您可以在List<PersonInfo>之后用people =轻松投射它

答案 3 :(得分:0)

public List<PersonInfo> printPersonInfo() {    
       List<PersonInfo> people = personRepo.findAll()
                                           .stream()
                                           .collect(Collectors.toList());
       System.out.println(people.toString());
       return people ;
}