【问题标题】:How to findAll entires(posts) which contain at least one specified tag. Spring Data如何查找包含至少一个指定标签的所有条目(帖子)。弹簧数据
【发布时间】:2015-04-01 15:27:28
【问题描述】:

我正在尝试仅检索具有特定标签的条目(帖子)。一个条目可以有多个标签,所以我使用对象列表。但是我不知道如何在 Controller 类中构造一个正确的命令,实际上我怕我完全迷失了这里。

条目实体如下所示:

@Entity
public class BlogEntry {

@Id
@GeneratedValue
private Integer id;

private String title;

@Column(name = "published_date")
private Date publishedDate;

@ManyToMany
@JoinTable
private List<TagBlog> blogTags; /* Multiple tags to one entry */

还有我的标签实体:

@Entity
public class TagBlog {

@Id
@GeneratedValue
private Integer id;

private String tag;

@ManyToMany(mappedBy="blogTags")
private List<BlogEntry> entries;

在我的 EntryService 类中,我想执行这种排序“findByTagBlogIn”,我希望它会返回具有特定标签的帖子列表。

public List<BlogEntry> findAllByTags(List<TagBlog> tag){                            

    List<BlogEntry> blogEntry = entryRepository.findByTagBlogIn(tag);

    return blogEntry;
}

但我不知道如何在 Controller 类中引用它。如何仅检索具有特定标签的条目?像这样的东西?但是如何将标签列表作为参数传递,也许应该是字符串?

@RequestMapping(value="/welcome")
public String retrieveTaggedEntry(Model model, ?List of tags?){

model.addAttribute("entriesWithTag", entryService.findAllByTags(TagBlog tag));

    return "redirect:/welcome.html"; 
}

在welcome.jsp 文件中,我想遍历已分配给特定条目(帖子)的整个标签列表,如下例所示(箭头之间的“--->

<c:forEach items="${entries}" var="entry"> <!--"entries" refers to List of BlogEntry-->
<table>
            <tr>
                    <td>Entry No. ${entry.id }</td>
                    <td>${entry.title}</td>
                    <td>
                    Tags: ---> #${entry.? blogTag.tag ?}, <--- 
                    </td>
                    <td>Published: ${entry.publishedDate}</td>
                    <td>
                        <spring:url value="/delete_entry/${entry.id}.html" var="url" />
                        <a href="${url}">Delete</a>
                    </td>
            </tr>
        </table>
</c:forEach>

通过稍后解决,我想通过拥有特定标签的条目执行排序(通过映射 spring:url value="/tag/${some_tag_as_a_String}.html")。

也许有一种更简单的方法可以只返回带有特定标签的帖子?但我想用我在这里得到的东西对我来说会更容易。无论如何,我们感谢您提供的任何解决方案。

如果需要,我愿意添加任何其他信息。

【问题讨论】:

    标签: java spring jsp spring-data spring-data-jpa


    【解决方案1】:

    您是否有任何理由要将整个TagBlog 对象发送到控制器?为什么不只是标签 ID 或标签文本?例如

    @RequestMapping(value="/welcome")
    public String retrieveTaggedEntry(Model model, @RequestParam List<String> tags) {
        // Do something with your tags
    }
    

    【讨论】:

    • 没有具体原因。让我检查一下我可以用 List 做什么以及它在控制器类中的工作原理。
    • 好吧,看起来我不能使用 List 因为它会引发错误:原因:org.hibernate.MappingException:无法确定类型:java.util.List,在表中:BlogEntry,用于列:[org.hibernate.mapping.Column(stringTag)]
    猜你喜欢
    • 2015-05-10
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多