简体   繁体   中英

findBy foreign key in Spring Data JPA

I have an entity EncodingResult that references three others. I want to find out how to use the repository's findBy() methods to return an entity based on its foreignKey so that I can, for example, make a GET request passing a Video's foreign key as a parameter and return whether or not there is an EncodingResult containing a Video with the given foreignKey .

How would you go about doing this? I tried reading a bit on EntityGraphs and was rather confused. There also doesn't seem to be a great number of content explaining these parts of the framework.

It would be better if you posted the code for your entities, but from your description, I think you have something like this:

@Entity
public class EncodingResult {

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

  @OneToMany(mappedBy = "encodingResult")
  private List<Video> videos=new ArrayList<Video>();

  //...boilerplate
}
@Entity
public class Video {

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

  private String name;

  @ManyToOne
  EncodingResult encodingResult;

  //...boilerplate
}

So you can define findBy methods in your EncodingResultRepository like so.

public interface EncodingResultRepository extends JpaRespository<EncodingResult, Integer> {

  public Optional<EncodingResult> findByVideoName(String name);

  public Optional<EncodingResult> findByVideoId(Integer id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM