Search code examples
javaspring-bootjpaone-to-manyfindby

findBy property in List<Object> SpringBoot JPA Repository


I have a one to many relationship between two objects in my database Story and Tag.

I'm looking to to be able to get all Story objects that have a Tag object with the String name.

Story.java

@Entity
@Table(name = "stories")
public class Story  {

    @Id
    @GeneratedValue
    private Long id;

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

    @JsonIgnoreProperties({"story"})
    @OneToMany(mappedBy = "story", fetch = FetchType.LAZY)
    private List<Tag> tags;

    public Story(String title){
        this.title = title;
    }

    public Story(){

    }

// getters & setters

}

Tag.java

@Entity
@Table(name = "tags")
public class Tag {

    @Id
    @GeneratedValue
    private Long id;

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

    @JsonIgnoreProperties({"tags"})
    @ManyToOne
    @JoinColumn(name = "story_id", nullable = false)
    @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
    private Story story;

    public Tag(String name, Story story){
        this.name = name;
        this.story = story;
    }

    public Tag(){

    }

/// getters & setters

}

StoryController.java

@RestController
public class StoryController {
    @Autowired
    StoryRepository storyRepository;

    @CrossOrigin(origins = "http://localhost:8080/api")
    @GetMapping(value = "/stories")
    public ResponseEntity<List<Story>> getAllStories(){
        return new ResponseEntity<>(storyRepository.findAll(), HttpStatus.OK);
    }

    @CrossOrigin(origins = "http://localhost:8080/api")
    @GetMapping(value="/stories/tagSearch/{name}")
    public ResponseEntity<Story> getStoryByTag(@PathVariable String name) {
        return new ResponseEntity(storyRepository.findByTags_Name(name), HttpStatus.OK);
    }

    @CrossOrigin(origins = "http://localhost:8080/api")
    @GetMapping(value="/stories/{id}")
    public ResponseEntity<Story> getStory(@PathVariable Long id) {
        return new ResponseEntity(storyRepository.findById(id), HttpStatus.OK);
    }

}

StoryRepository.java

@Repository
public interface StoryRepository extends JpaRepository<Story, Long> {

    public List<Story> findByTags_Name(String name);

}

When trying to query through the browser, going to the address localhost:8080/api/stories/tagSearch/?name="tag" the database returns all objects in the database rather than the results I'm looking for.


Solution

  • You need to use the below method in your repository.

    public List<Story> findByTagsName(String name);
    

    You need to use the following URL to fetch the details, as you have defined the name as PathVariable

    localhost:8080/api/stories/tagSearch/tag
    

    tag - is your name