spring-data-jpa 如何在Sping Boot 中以列表的形式获取包含列数据的MySQL表?

dffbzjpn  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(99)

我有一个这样的控制器,它给仓库字段下命令。

@RestController
@RequestMapping (path="/quex")
public class CommentController {

  @Autowired
  CommentRepository repository;

  @GetMapping(path="/list")
  public List<String> getAllUser () {

    return repository.getUserAll();
  }
}

然后,我定义了在MySQL服务器上进行事务的存储库部分,如下所示。

@Repository
public class CommentRepository {

  @Autowired
  JdbcTemplate jdbcTemplate;

  public List<String> getUserAll () {

    List<String> users = new ArrayList<>();

    users.addAll(jdbcTemplate.queryForList("select * from users", String.class));

    return users;
  }
}

我想得到它的形式完全一样的列表在底部。

{
"name": "Thunder",
"lastname": "Paxis",
}
s6fujrry

s6fujrry1#

You should create a POJO that matches the columns from your users tables and use it as casting.

public class User {
  // private Long id; // did not see it in your json but assuming it exists in DB and you would need it if select *
  private String name;
  private String lastName;

  // Getters and setters...
}

You can skip any column you don't want in the POJO but it needs to match the SQL query. Meaning, if you select * from users you need all columns but you can select name, lastname from users if you want just those 2.
There might also be some casing issues. Java usually uses camel case so it often confuses me if we have to use camel case for the library to match the column or not.
Anyways... Now you can update your code with:

@GetMapping(path="/list")
public List<User> getAllUser () {
  return repository.getUserAll();
}

...

public List<User> getUserAll () {
  List<User> users = new ArrayList<>();
  users.addAll(jdbcTemplate.queryForList("select * from users", User.class));
  return users;
}

One last note, User might not be the best name for the class as your project probably has 10 to 15 classes with this name already in your dependencies... It will work just fine but be sure to import the correct one ;)

相关问题