最近弄book的增改花了不少时间,主要是在bookType上花的时间较多。
Book
@Entity
@Table(name="T_Book")
@DynamicInsert(true)
@DynamicUpdate(true)
public class Book implements java.io.Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="BookId")
private int BookId;
//虚拟属性,每次查询时,还要查询有多少本书,可借多少本,然后赋值,这样book就能添加这两个参数了
@Transient
private int totalNum;//馆藏数
@Transient
private int canBorrowNum;//可借数
/**
* 用于业务逻辑的字段,注解@Transient代表不需要持久化到数据库中
*/
@ManyToOne
<span style="white-space:pre"> </span>@JoinColumn(name="BookTypeId") //重点!!!!!!!!!!!!!
private BookType BookType;
//抓取策略为EAGER,要不然bookService统计有多少本书时错误。
@OneToMany(mappedBy="Book",cascade=(CascadeType.ALL), fetch=FetchType.EAGER)
private Set<BookSN> BookSNs;
@Column(name="BookName")
private String BookName;
//省略部分属性和set,get函数
}
@Entity
@Table(name="T_BookType")
@DynamicInsert(true)
@DynamicUpdate(true)
public class BookType implements java.io.Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="BookTypeId")
private int BookTypeId;
@Column(name="BookTypeName")
private String BookTypeName;
@Column(name="BookTypeCode")
private String BookTypeCode;
@OneToMany(mappedBy="BookType")
private Set<Book> Books;
//省略get和set函数
}
jsp(用html创建而不是jquery):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ include file="/common/base.jsp"%> <%--前面加了/就是代表绝对路径,即包含了localhost+端口号+项目名 --%>
<script type="text/javascript">
var url;
function newBook(){
$('#dlg').dialog('open').dialog('setTitle','添加书籍');
$('#fm').form('clear');
document.getElementById("fieldBookID").style.visibility="hidden"; //这里书籍id是自增长,所以不用显示id字段
url = 'book/addBook';
}
function editBook(){
var row = $('#dg').datagrid('getSelected');
// alert(row.userId);
if (row){
$('#dlg').dialog('open').dialog('setTitle','编辑书籍');
$('#fm').form('load',row);
//解决编辑是不能显示书类型问题 这里要注意的是设置combox的值是bookTypeId而不是bookTypeName,因为传到后台是要bookTypeId的而//不是bookTypeName!!!!!!!!!!!!!!!
if(row.bookType.bookTypeName!=null){
$('#formBookType').combobox('setValue',row.bookType.bookTypeId);
}
url ='book/updateBook';
}
}
function saveBook(){
$.post(url, sy.serializeObject($('#fm')), function(result) {
if (result.success) {
$.messager.show({
title:'Info',
msg:result.msg,
showType:'fade',
style:{
right:'',
bottom:''
}
});
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({
title: 'Error',
msg: result.msg
});
}
}, 'json');
}
function doSearch(){
$('#dg').datagrid('load',{
queryBookName: $('#searchBox').val()
});
}
function clearSearch(){
$('#searchBox').val('');
$('#dg').datagrid('load',{});
}
//这里因为不能再field里面直接用bookType.bookTypeName,所以要用formatter!!!!!!!
function formatBookType(val,row,index){
//alert(row.bookType);
if(row.bookType==null){
return "";
}else
return row.bookType.bookTypeName;
}
</script>
</head>
<body class="easyui-layout" data-options="fit:true,border:false">
<table id="dg" class="easyui-datagrid" data-options="fit:true,border:false"
url="book/listBookForUser"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="bookId" value= width="50">书ID</th>
<th field="bookName" width="50">书名</th>
<th field="bookType.bookTypeName" width="50" formatter="formatBookType">书类型</th>
<th field="author" width="50">作者</th>
<th field="callNumber" width="50">索书号</th>
<th field="iSBN" width="50">ISBN</th>
<th field="publisher" width="50">出版社</th>
<th field="publishYear" width="50">出版年份</th>
<th field="series" width="50">系列</th>
<th field="language" width="50">语言</th>
<th field="price" width="50">价格</th>
<th field="page" width="50">页数</th>
</tr>
</thead>
</table>
<div id="toolbar">
<br>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-add" plain="true" οnclick="newBook()">New Book</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" οnclick="editBook()">Edit Book</a>
<div>
<span>BookName:</span>
<input id="searchBox" style="line-height:26px;border:1px solid #ccc">
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-search" plain="true" οnclick="doSearch()">Search</a>
<td><a href="javascript:void(0);" class="easyui-linkbutton" iconCls="ext-icon-zoom_out" plain="true" οnclick="clearSearch()">清空查询</a></td>
</div>
</div>
<div id="dlg" class="easyui-dialog" style="width:300px;height:350px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<form id="fm" method="post" novalidate>
<table cellpadding="5">
<div class="fitem" id="fieldBookID">
<label>书ID:</label>
<input name="bookId" readonly="readonly">
</div>
<div class="fitem">
<label>书名:</label>
<input name="bookName" class="easyui-validatebox" required="true" >
</div>
<label>书类型:</label> <!--这里极其注意每一个字段。select name为bookTypeId ->
<select name="bookType.bookTypeId" id="formBookType" class="easyui-combobox" data-options="required:true,editable:false,valueField:'bookTypeId',textField:'bookTypeName',url:'bookType/getBookType',panelHeight:'auto'" style="width: 155px;"></select>
<div class="fitem">
<label>作者:</label>
<input name="author">
</div>
//省略部分属性!!!!!!!!!!!!!!!!
</table>
</form>
</div>
<div id="dlg-buttons">
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-ok" οnclick="saveBook()">Save</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-cancel" οnclick="javascript:$('#dlg').dialog('close')">Cancel</a>
</div>
</body>
</html>
jsp要注意的地方很多。。。其中saveBook函数那里,提交的表单是序列化的:
$.post(url, sy.serializeObject($('#fm')), function(result) {}
其中这个序列化函数是扩展的(用的是孙宇的):
/**
* 将form表单元素的值序列化成对象
*
* @example sy.serializeObject($('#formId'))
*
* @author 孙宇
*
* @requires jQuery
*
* @returns object
*/
sy.serializeObject = function(form) {
var o = {};
$.each(form.serializeArray(), function(index) {
if (this['value'] != undefined && this['value'].length > 0) {// 如果表单项的值非空,才进行序列化操作
if (o[this['name']]) {
o[this['name']] = o[this['name']] + "," + this['value'];
} else {
o[this['name']] = this['value'];
}
}
});
return o;
};
这样后台直接用 Book book就能自动的传参,而不用手动的接受book的属性:
@RequestMapping("/addBook")
public String addBook(Book book,HttpServletRequest request,
HttpServletResponse response) throws Exception{.............<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
BookController:
@Controller
@RequestMapping("/book")
public class BookController extends BaseController {
@Autowired
private IBookService bookService;
@RequestMapping("/borrow")
/**
* 用于管理员查询和添加书籍
* @param request
* @param response
* @return 书籍基本信息列表
* @throws Exception
*/
@RequestMapping("listBookForUser")
public String listBookForUser(HttpServletRequest request,
HttpServletResponse response) throws Exception {
page=ServletRequestUtils.getIntParameter(request, "page", 1);//默认值为1
rows=ServletRequestUtils.getIntParameter(request, "rows", 0);
String queryBookName=request.getParameter("queryBookName");//获取要查询的用户账号
// System.out.println(queryBookName);
Grid grid = new Grid();
String hql=null;
long totalNum;
List<Book>books;
if(queryBookName!=null)
{
hql="from Book as book where book.BookName like '%"+queryBookName+"%'";
}else{
hql="from Book";
}
books=(List<Book>)bookService.find(hql, page, rows);
totalNum=bookService.count("select count(*)"+hql);
grid.setTotal(totalNum);
grid.setRows(books);
writeJson(grid,response);
return null;
}
@RequestMapping("/goAddBook")
public ModelAndView goAddBook(){
return new ModelAndView("book/addBook");
}
/**
* 管理员添加书籍
* @param book
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/addBook")
public String addBook(Book book,HttpServletRequest request,
HttpServletResponse response) throws Exception{
Json json = new Json();//用于向前端发送消息
//这里怎么判断一本书是否存在? ISBN不同版次可能一样么?
//if(bookService.getById(book.getBookId())!=null){
// json.setMsg("添加书籍失败,用户已存在!");
//}else{
System.out.println("34657");
bookService.save(book);
json.setMsg("添加书籍成功!");
json.setSuccess(true);
// }
writeJson(json,response);
return null;
}
@RequestMapping("/updateBook")
public String updateBook(Book book,HttpServletResponse response) throws Exception{
Json json = new Json();//用于向前端发送消息
try{
bookService.update(book);
json.setMsg("更新成功!");
json.setSuccess(true);
}catch(Exception e){
json.setMsg("更新失败!"+e.getMessage());
}
writeJson(json,response);
return null;
}
}