【问题标题】:Get child count using hibernate in springmvc在spring mvc中使用hibernate获取孩子计数
【发布时间】:2016-06-08 12:50:15
【问题描述】:

如果我们正在为网站创建后端。我们显然会创建类别和帖子/产品。要添加/编辑/删除类别,我们显然会创建一个类似表的结构。例如:This is category listing as table

Category 在同一个表中会有一个子类别,子类别的数量可以是 1 - many。我想显示上图中提到的子类别的数量。

作为一名 CI 开发人员,我过去常常通过在视图中使用 Query 来做到这一点,

这是一个例子

<?php 
            if(sizeof($results)>0)
                {     
                $i=1;

                foreach($results as $key => $list)
                  {


                  if($i%2==0)$cls="row1"; else $cls="row2";   
            ?>       
            <tr id="<?php echo $list->id;?>" class="<?php echo $cls; ?>">    
                <td> <?php echo $list->title, anchor("admin/categories/update/".$list->id."/", '<i class="fa fa-pencil rtrt"></i>' ); ?></td>

                <td> 

                     <?php 
                        // it will return number of childs
                         echo anchor ('admin/categories/category/'.$list->id, $this->Common->select_child ('tbl_category', $list->id) );
                     ?>
                </td>

现在我正在使用 Spring-mvc、hibernate、Jpa 和 Mysql DB。我知道从 jsp 进行 sql 查询是一种不好的做法。

这是我的表格结构的 Jsp 代码,

<table class="table table-striped">
    <thead>
    <tr>
         <th><i class="fa fa-pencil"></i></th>
         <th>Category Name</th>
         <th>Child</th>
         <th>Created</th>
         <th>Updated</th>
         <th><input type="checkbox" /></th>
    </tr>
    </thead>
    <tbody>
    <c:if test="${not empty category}">
          <c:forEach var="cat" items="${category}">
            <tr>
                 <td><a href="${pageContext.request.contextPath}/category/${cat.id}/edit"><i class="fa fa-pencil"></i></a></td>
                 <td>${cat.title}</td>
                 <td><a href="${pageContext.request.contextPath}/category/show/${cat.id}"><i class="fa fa-folder-open"></i></a></td>
                 <td>${cat.created}</td>
                 <td>${cat.updated}</td>
                 <td><input type="checkbox" /></td>
            </tr>
        </c:forEach>
    </c:if>

这里是类别 POjo 类

@Entity
@Table(name = "categories")
public class Categories {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

private Long parent_id;

private String title;

private String url_title;

private String description;

private String created;

private String updated;

/* 
 * @ At the time of Creating new user
 * Auto persist created date
 * Auto persist updated for first time
 */
@PrePersist
protected void onCreate (){

    // Date conversion to string
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm:s");
    sdf.setLenient(false);
    String now = sdf.format(date);

    created = now;
    updated = now;


}


/*
 *  Respective Getter and Setter Methods
 *  
 */
public Long getId() {
    return id;
}public void setId(Long id) {
    this.id = id;
}

public Long getParent_id() {
    return parent_id;
}public void setParent_id(Long parent_id) {
    this.parent_id = parent_id;
}

public String getTitle() {
    return title;
}public void setTitle(String title) {
    this.title = title;
}

public String getUrl_title() {
    return url_title;
}public void setUrl_title(String url_title) {
    this.url_title = url_title;
}

public String getCreated() {
    return created;
}public void setCreated(String created) {
    this.created = created;
}

public String getUpdated() {
    return updated;
}public void setUpdated(String updated) {
    this.updated = updated;
}

public String getDescription() {
    return description;
}public void setDescription(String description) {
    this.description = description;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Categories other = (Categories) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    return true;
}

问题是

如何在不从 Jsp 执行 sql 查询的情况下获取孩子数? 请帮助我,我需要一个建议。

【问题讨论】:

  • 可以添加分类实体plez吗?
  • 我刚刚添加了分类类?你能建议我,如何实现我所需要的。
  • 我已经发布了一个答案,但我不知道你的真正意思是:children count
  • 考虑一个服装网站类别的示例,该类别将具有价值,例如(男装、童装、女装),其中儿童将是 T 恤、牛仔裤、衬衫。
  • 像这样:@OneToMany private List&lt;Categories&gt; subCategories;

标签: java spring hibernate spring-mvc jpa


【解决方案1】:

要在 jsp 端获取列表计数,请使用如下 jstl 函数:

声明jstl.functions的标签

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

那你可以试试这个

<c:set var="count" value="${fn:length(you_array)}" />

这将创建一个变量"count" 作为值:you_array.size()

【讨论】:

    【解决方案2】:

    希望它能帮助像我这样的人,

    修改实体类

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;
    
    private Long parent_id;
    private String title;
    private String url_title;
    private String description;
    private Long status;
    private String created;
    private String updated;
    
    @ManyToOne 
    @JoinColumn(
    name="parent_id", 
    insertable=false, 
    updatable=false) 
    @NotFound(action = NotFoundAction.IGNORE)
    private Categories parentCategory;
    
    @OneToMany(
    fetch = FetchType.EAGER, 
    mappedBy="parentCategory", 
    cascade=CascadeType.REMOVE, 
    orphanRemoval=true )
    
    private Set<Categories> child = new HashSet<Categories>();
    

    由于我是 Jpa/orm/hibernate/spring 的新手,所以当我发布这个问题时,我不知道我们可以在 hibernate 中管理的实体关系。我做了一些研究,发现使用 注释一对多,多对一,多对多强>)。我建议如果您是 JPA 和 hibernate 的新手,请在浪费时间之前访问This link

    我做了什么

    与 join 的双向关联: 使用 @ManyToOne @Onetomany @joinColumn

    使用 @NotFound(NotFoundAction.IGNORE) 解决 Notfound 异常 我有一个类别(例如基本类别),它没有任何父类别,因此它的“parent_id”在数据库中将为 0,但在成功关联后,当从 id 为 0 的数据库中查询记录时,Hibernate 会抛出异常。

    Used insertable/updatable = false : 如果您一次只插入和更新一个类别,请将此属性设置为 false。

    Used "cascade=cascadetype.remove" "orphanremoval=true" :设置此属性,如果您想在删除父类别时删除子类别。当您调用 serviceImplementation.delete(category cat) 方法时,如果 "cat:object" 是其他类别的父类别,休眠将在删除 cat:object 本身之前自动删除它的子类别。

    我的问题终于有了答案

    与注解关联成功后,何时从数据库中查询类别行。如果它是其他类别的父类别,休眠将像这样在您的对象中添加 "child Collection"

    03:20:16.490 [http-bio-8080-exec-5] DEBUG
    o.h.internal.util.EntityPrinter -
    com.pack.librarymanagementsystem.model.Categories
    {created=2016-06-10 7:45:32, parent_id=38, url_title=Bhm 5th sem, 
    description=<p>asd</p>,
    parentCategory=com.pack.librarymanagementsystem.model.Categories#38,
    id=43, title=Bhm 5th sem, updated=2016-06-10 7:45:32, child=[], status=1}
    

    如果您使用的是 Eclipse,请在控制台日志中检查它。刚刚添加的子集合 hibernate 不会有任何数据。 Hibernate 将只存储代理。

    解决方案是获取子集合的大小。

    如果您对那个子集合执行 isEmpty() 检查,结果将为真。这就是 "fetch = FetchType.EAGER" 发挥作用的地方。默认情况下,fetchtype 设置为惰性。将 fetchtype 更改为 eager hibernate 后,会将对象添加为子对象,而不是添加代理。

    如果您现在对那个子集合进行 isEmpty 检查,结果将是错误的。这意味着我们可以获得集合的大小。

    这是jsp

    <c:if test="${not empty category}">
    <c:forEach var="cat" items="${category}">
    <tr>
        <td><a href="${pageContext.request.contextPath}/category/${cat.id}/edit"><i class="fa fa-pencil"></i></a></td>
        <td>${cat.title}</td>
        <td>
            // Child count
            <c:if test="${not empty cat.child}" >
                <a href="${pageContext.request.contextPath}/category/show/${cat.id}">
                    <i class="fa fa-folder-open"></i> ${ fn:length(cat.child)}
                </a>    
            </c:if>
            <c:if test="${empty cat.child}" >
                <i class="fa fa-folder"></i> 0
            </c:if>
        </td>
        <td>${cat.created}</td>
        <td>${cat.updated}</td>
        <td>
            <c:choose>
                <c:when test="${cat.status == 1}">Published</c:when>
                <c:otherwise>Unpublished</c:otherwise>
            </c:choose>
        </td>
        <td><input type="checkbox" name="ids[]" id="ids[]" value="${cat.id}" /></td>
    </tr>
    </c:forEach>
    

    这是控制器

    @RequestMapping(value = "/show/", method = RequestMethod.GET)
    public String viewCategory( Map<String, Object> model) {
    
    List<Categories> category = categoryService.getAllCategoriesByParent(Id); 
    model.put("category",category);
    
    return "category/view";
    }
    

    我希望这可以帮助某人节省他/她的时间。 谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2017-09-26
      • 1970-01-01
      • 2012-03-25
      • 2013-09-03
      • 2017-01-03
      相关资源
      最近更新 更多