Java Spring Get Item By User Id

In my JavaSpring API project, I encountered a problem with retrieving all “Finances” by user ID. I wanted to send a request to the API with a body containing the user ID and get back all the finances associated with that user.

I have an entity class called Finance which looks like this:

@Entity
@Table(name = "finance")
public class Finance {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private User user;

    @Column(nullable = false)
    private String title;

    private String description;

    @Column(nullable = false)
    private String date;

    @Column(nullable = false)
    private Integer value;
}

I tried to implement a method in my service class to get finances by user ID, but I got stuck. Here is what my service class looks like:

public ResponseEntity<Object> GetFinanceByUserId(Integer userId) {
    List<Finance> userFinances = financeRepository.findByUserId(userId);
    return new ResponseEntity<>(userFinances, HttpStatus.OK);
}

To solve this issue, I created a repository interface for the Finance entity:

public interface FinanceRepository extends JpaRepository<Finance, Integer> {
    List<Finance> findByUserId(Integer userId);
}

By using the findByUserId method in the repository, I was able to retrieve all finances associated with a specific user ID. This helped me to successfully implement the functionality to get all “Finances” by user ID in my JavaSpring API project.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *