javajpaspring-data-jpaormjparepository

JPA: How to get an entity by the id of another object?


Client Entity:

@Entity
@Table(name = "CLIENT")
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "trainer_id")
    private Trainer trainer;
    
    @JsonBackReference
    public Trainer getTrainer() {
        return trainer;
    }

    public void setTrainer(Trainer trainer) {
        this.trainer = trainer;
    }
    
    // other getters and setters
    
}

Trainer Entity:

@Entity
@Table(name = "TRAINER")
public class Trainer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

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

    @OneToMany(mappedBy = "trainer", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Client> clients;
    
    public Trainer() {}
    
    @JsonManagedReference
    public List<Client> getClients() {
        return clients;
    }

    public void setClients(List<Client> clients) {
        this.clients = clients;
    }
    
    // other getters and setters
    
    }

Repository:

public interface ClientRepository extends JpaRepository<Client, Long> {}

How can I get the a client entity by trainerId?


Solution

  • Spring has some cool features when it comes to methods that can be autogenerated. Something I've done in the past to do this type of thing is create a method inside of ClientRepository.

    public Client findByTrainer_Id(int trainerId);
    

    As long as this method is named correctly, JPA can create the query itself and fetch the client

    This should hopefully fix your issue, the method could then be called inside your controller using your ClientRepository