2016-06-08 63 views
0

如果我們正在爲網站創建後端。我們顯然會創建類別和帖子/產品。要添加/編輯/刪除類別,我們顯然會創建一個類似於結構的表格。例如:This is category listing as table在springmvc中使用hibernate獲取子女人數

類別在同一個表中具有子類別,子類別的數量可以是1 - 許多。我想顯示上面圖片中提到的兒童類別的數量。

作爲CI開發商我用在視圖中使用查詢要做到這一點,

這裏是例子

<?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,休眠, 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查詢? 請幫助我,我需要一個建議。

+0

你能添加categorie實體pleaz嗎? –

+0

我剛添加了類別類?你可以請建議我,如何實現我所需要的。 –

+0

我v發佈了一個答案,但我不知道你真正的意思是:**兒童數量** –

回答

0

獲得JSP的一側使用JSTL的功能列表計數象下面這樣:

聲明jstl.functions的taglibe

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

,那麼你可以試試這個

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

這將創建一個變量"count"作爲值:you_array.size()

0

希望這將有助於我這樣的人,

修改實體類

@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中管理的關係。我做了一些研究,發現冬眠'單向/雙向'協會使用註釋像(一對多,多對一,多對多)。我建議如果你是JPA和休眠的新手,那麼請在浪費你的時間之前訪問This link

我做了什麼

雙向關聯與加盟:使用@ManyToOne @OneToMany @JoinColumn

解決使用@NotFound(NotFoundAction.IGNORE)NOTFOUND例外 我有一個類別(例如Base類別)不會有任何父類別,所以它的'parent_id'在數據庫中將爲0,但Hibernate會在從ID爲0的數據庫查詢記錄時拋出異常,之後一個成功的協會。

使用insertable/updatable = false:如果您一次僅插入和更新一個類別,則將此屬性設置爲false。

使用「cascade = cascadetype.remove」「orphanremoval = true」:設置此屬性,如果要在刪除父類別時刪除子類別。當你調用serviceImplementation.delete(category cat)方法時,如果「cat:object」是其他類別的父類,hibernate會在刪除cat:object本身之前自動刪除它的子類別。

最後,回答我的問題

與註釋的成功關聯,當你從數據庫中查詢類別行之後。如果它是其他類別的父類別,hibernate會在您的對象中添加「子集合」

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將只存儲proxys。

解決方法是獲取子集合的大小。

如果您會這樣做isEmpty()檢查該子集合的結果將是true。那就是「fetch = FetchType.EAGER」開始。默認情況下,fetchtype設置爲lazy。在將fetchtype更改爲渴望之後,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"; 
} 

我希望這將有助於有人在救了他/她的時間。 謝謝