Home > Back-end >  How can I get the MySQL table with column data in the form of a list in spring boot?
How can I get the MySQL table with column data in the form of a list in spring boot?

Time:09-22

I have exactly such a controller and it gives orders to the repository field.

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

  @Autowired
  CommentRepository repository;

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

Then I defined the repository part that makes transactions on my MySQL server like this.

@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;
  }
}

I want to get it exactly in the form of the list at the bottom.

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

CodePudding user response:

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 ;)

  • Related