Home > Mobile >  JpaRepository .findAll method returns null values and reapeating list via postman
JpaRepository .findAll method returns null values and reapeating list via postman

Time:06-01

So I am creating a simple stock management project, however, when I query the DB (MySQL) the .findall() method returns the first row multiple times and some column data is null when data is evidently present. Please note, I am using Lombok also.

In addition to the same row being returned, 3 new columns are created every time the query is run. I feel it could be a mapping issue from entity field to DB column, but everything seems to mathc for me?

Can provide further info if needed.

Entity

@Entity
@Data
//@NoArgsConstructor
@Table(name = "users")
public class UserModel {

    @Id
    @GeneratedValue
    private Long ID;
    @Column(name = "userId", nullable = false)
    private Long userId;

    @Column(name = "FirstName", nullable = false)
    private String FirstName;
    @Column(name = "LastName", nullable = false)
    private String LastName;
    @Column(name = "Address", nullable = false)
    private String Address;
    @Column(name = "Mobile", nullable = false)
    private String Mobile;
    @Column(name = "Email", nullable = false)
    private String Email;
    @Column(name = "LastLogin", nullable = false)
    private Date LastLogin;
    @Column(name = "LastUpdated", nullable = false)
    private Date LastUpdated;
}

UserService

@Override
public List<UserModel> getAllUsers() {
    return userRepo.findAll();
}

Controller

 @GetMapping("/getAll")
public ResponseEntity<List<UserModel>> getallUsers(){
    List<UserModel> userModels = (List<UserModel>) userService.getAllUsers();
    return new ResponseEntity<List<UserModel>>(userModels, HttpStatus.OK);
}

CodePudding user response:

If the default implementation of JpaRepository#findAll fails (for whatever reason), try your own:

@Repository
public interface UserModelRepository extends JpaRepository<UserModel, Long> {

    @Override
    @Query("SELECT um FROM UserModel um")
    List<UserModel> findAll();

}

Note: The query in this example is the same as what JPA generates by default. It should be actually overriden depending on the requirement.

Also, there's no need to cast in your controller. The getAllUsers() method already returns a List<UserModel>.

CodePudding user response:

Thank you for your answers, it is appreciated and will give me further angles to keep in mind on future debugging.

The way I solved it in the end was updating the table column names to snake case, i.e. "FirstName" was changed to "first_name". So in hindsight, the mapping was the issue.

  • Related