Posted on 2008-03-17 12:09
云自無心水自閑 閱讀(5785)
評論(8) 編輯 收藏 所屬分類:
Java 、
Struts2
在數據庫的設計中,字典項是經常使用的技巧。
比如在一個圖書館系統中,書籍表(Book)會有一個分類字段,這時候我們一般會單獨建立一張分類表(Category),在書籍表只保存分類表的ID。
在用戶界面上顯示書籍明細的時候,會要求顯示CategoryID在Category表中對應的名稱。
這樣通常的做法是把Book和Category兩張表進行關聯。
但在實際應用中,Category一般都是Cache在應用服務器端,再使用數據表的連接就不夠高效。
我的做法是這樣的:在iBatis中使用SqlMap從表中將數據取出,此時不使用數據表的連接。
package com.demo;
public class Book {
/* 省略了getter和setter方法 */
private int id;
private String name;
private int categoryId;
private String author;
}
package com.demo;
public class Category {
private static Map<Integer, Category> cacheMap;
/* 省略了這兩個屬性的getter和setter方法 */
private int id;
private String name;
public static Category getCategory(int id) {
init();
return cacheMap.get(id);
}
public static Map<Integer, Category> getCategoryMap() {
init();
return cacheMap();
}
private init() {
if ( cacheMap != null ) return;
// the code to load category from datebase
// 在這里為了演示的需要,使用以下代碼
cacheMap = new HashMap<Integer, Category>();
Category category = new Category();
category.setId(1);
category.setName("Fiction");
cacheMap.put(1, category);
category = new Category();
category.setId(2);
category.setName("Cartoon");
}
}
package com.demo;
public class BookAction {
/* 省略了屬性的getter和setter方法 */
Book book;
public String execute() {
book = new Book();
book.setId(1);
book.setName("Thinking in java");
book.setCategoryId(1);
bookList.add(book);
return SUCCESS;
}
}
JSP:
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<s:head />
</head>
<body>
<table border="1">
<tr>
<td>
<s:text name="page.label.userName" />
</td>
<td>
<s:property value="book.name" />
</td>
</tr>
<tr>
<td>
<s:text name="page.label.category" />
</td>
<td>
<s:property value="@com.demo.Category@getCategory(book.categoryId).getName()"/></td>
</tr>
</body>
</html>