findby属性

yrdbyhpb  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(333)

我的数据库story和tag中的两个对象之间有一对多关系。
我希望能够得到所有的故事对象,有一个字符串名称标记对象。
故事.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

}

标签.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

}

故事控制器.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);
    }

}

故事库.java

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

    public List<Story> findByTags_Name(String name);

}

当试图通过浏览器进行查询时,转到localhost:8080/api/stories/tagsearch/?name=“tag”数据库返回数据库中的所有对象,而不是我要查找的结果。

pprl5pva

pprl5pva1#

在存储库中执行此操作

@Query("SELECT s FROM Story s left join s.tags t WHERE t.name = ?1")
public List<Story> findByTags_Name(String name);
c86crjj0

c86crjj02#

你需要使用下面的方法 repository .

public List<Story> findByTagsName(String name);

您需要使用以下url来获取详细信息,因为您已经定义了 name 作为 PathVariable ```
localhost:8080/api/stories/tagSearch/tag

你叫什么名字

相关问题