简单CRUD

Item.java

package cn.com.manage.entity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="ITEM2")
public class Item implements Serializable{

    private static final long serialVersionUID = 1L;
    
    @GenericGenerator(name = "generator", strategy = "guid")
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "ID", unique = true, nullable = false, length = 38)
    private String id;
    
    @Column(name="ITEM_NUMBER",length=10)
    private String itemNumber;
    
    @Temporal(TemporalType.DATE)
    private Date startTime; 
    
    @Column(name="IS_OPEN",length=1)
    private String isOpen;
    
    @Column(name="MANAGER",length=50)
    private String manager;
    
    @Column(name="TEL",length=15)
    private String tel;
    
    @Column(name="INVERSTMENT",columnDefinition="number(20,3) default 0 ")
    private BigDecimal inverstment;
    
    @Column(name="FILEPATH",length=200)
    private String filepath;
    
    @Column(name="DESCRIPTION", columnDefinition="CLOB", nullable=true) 
    private String description;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItemNumber() {
        return itemNumber;
    }

    public void setItemNumber(String itemNumber) {
        this.itemNumber = itemNumber;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public String getIsOpen() {
        return isOpen;
    }

    public void setIsOpen(String isOpen) {
        this.isOpen = isOpen;
    }

    public String getManager() {
        return manager;
    }

    public void setManager(String manager) {
        this.manager = manager;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public BigDecimal getInverstment() {
        return inverstment;
    }

    public void setInverstment(BigDecimal inverstment) {
        this.inverstment = inverstment;
    }

    public String getFilepath() {
        return filepath;
    }

    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    public String getDescription() {
        return description;
    }

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

    
    
    

}

 

ItemDao.java

package cn.com.manage.dao;

import java.util.Map;

import cn.com.frame.common.DataGridModel;
import cn.com.frame.common.Page;
import cn.com.frame.dao.GenericDao;
import cn.com.manage.entity.Item;

public interface ItemDao extends GenericDao<Item,String>{

    /**
     * 根据分页查找项目列表
     * @param map
     * @param gridModel
     * @return 指定结果
     */
    Page<Item> getAllItem(Map<String, String> map, DataGridModel gridModel);
    
}

ItemDaoHibernate.java

package cn.com.manage.dao.impl;

import java.util.Map;

import org.hibernate.HibernateException;
import org.springframework.stereotype.Component;

import cn.com.frame.common.DataGridModel;
import cn.com.frame.common.Page;
import cn.com.frame.dao.impl.GenericDaoHibernate;
import cn.com.manage.dao.ItemDao;
import cn.com.manage.entity.Item;

@Component("ItemDao")
public class ItemDaoHibernate extends GenericDaoHibernate<Item, String> implements ItemDao{

    public ItemDaoHibernate() {
        super(Item.class);
    }

    @Override
    public Page<Item> getAllItem(Map<String, String> map,
            DataGridModel gridModel) {
        Page<Item> page = null;
        String hql = "from Item item order by item.id asc ";
        try {
            page = find(hql, null, gridModel);
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return page;
    }

}

ItemService.java

package cn.com.manage.service;

import java.util.Map;

import net.sf.json.JSONObject;
import cn.com.frame.common.DataGridModel;
import cn.com.manage.entity.Item;

public interface ItemService {

    /**
     * 获取分页项目
     * @param map
     * @param gridModel
     * @return 分页项目
     */
    JSONObject getAllItem(Map<String, String> map, DataGridModel gridModel);
    
    /**
     * 添加项目
     * @param item
     * @return 添加是否成功
     */
    boolean saveItem(Item item);
    
    /**
     * 根据项目Id获取项目
     * @param id
     * @return 返回项目
     */
    JSONObject getItem(String id);
    
    /**
     * 根据指定id删除项目
     * @param id
     * @return 删除操作布尔值
     */
    boolean deleteItem(String id);
}

ItemServiceImpl.java

package cn.com.manage.service.impl;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.frame.common.DataGridModel;
import cn.com.frame.common.DateJsonValueProcessor;
import cn.com.frame.common.JSONConfig;
import cn.com.frame.common.Page;
import cn.com.manage.dao.ItemDao;
import cn.com.manage.entity.Item;
import cn.com.manage.service.ItemService;

@Component("ItemService")
public class ItemServiceImpl implements ItemService{

    private ItemDao itemDao;

    @Autowired
    public void setItemDao(ItemDao itemDao) {
        this.itemDao = itemDao;
    }

    @Override
    public JSONObject getAllItem(Map<String, String> map,
            DataGridModel gridModel) {
        Page<Item> items=itemDao.getAllItem(map, gridModel);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        itemMap.put("total", items.getTotalResult());
        itemMap.put("rows", items.getResults());
        
        JSONObject  jsonObject = new JSONObject();
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm"));
        jsonObject  = JSONObject.fromObject(itemMap,config);
        return jsonObject;
    }

    @Override
    public boolean saveItem(Item item) {
        try{
            itemDao.save(item);
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public JSONObject getItem(String id) {
        Item item=itemDao.get(id);
        JSONObject object = new JSONObject();
        JsonConfig config = JSONConfig.getConfig();
        config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm"));
        object = JSONObject.fromObject(item,config);
        return object;
    }

    @Override
    public boolean deleteItem(String id) {
        try{
            itemDao.remove(id);
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }
    
    
}

ManageController.java

package cn.com.frame.controller;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.frame.common.DataGridModel;
import cn.com.manage.entity.Item;
import cn.com.manage.service.ItemService;

/**
 * 项目控制层
 */
@Controller
@RequestMapping("/manageController")
public class ManageController extends BaseController2{

    private ItemService itemService;
    
    @Autowired
    public void setItemService(ItemService itemService) {
        this.itemService = itemService;
    }


    @RequestMapping(value="/manageList")
    public ModelAndView toUserList(){
        return new ModelAndView("frame/manage/manageList_jsp");
    }
    
    /**
     * 所有分页项目
     * @param name
     * @param page
     * @param rows
     * @return 返回分页项目
     */
    @RequestMapping(value="/getAllItem",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject getAllItem(Integer page,Integer rows){
        DataGridModel gridModel = new DataGridModel();
        gridModel.setPage(page);
        gridModel.setRows(rows);
    
        JSONObject jsonObject = new JSONObject();    
         Map<String , String> map  = new HashMap<String, String>();
        jsonObject = itemService.getAllItem(map,gridModel);
        return jsonObject;
    }
    
    /**
     * 添加项目
     * @param user
     * @param role
     * @return
     */
    @RequestMapping(value="/addItem",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String addItem(Item item){
        boolean f=    itemService.saveItem(item);
        return f+"";
    }
    
    
    /**
     * 通过项目Id获取项目
     * @param id
     * @return
     */
    @RequestMapping(value="/getItem/{id}",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject getItem(@PathVariable("id")String id){
        JSONObject object = itemService.getItem(id);
        return object;
    }
    
    /**
     * 根据指定Id删除项目
     * @param id
     * @return 删除操作布尔值
     */
    @RequestMapping(value="/deleteItem/{id}",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public boolean deleteItem(@PathVariable("id")String id){
        boolean tag = itemService.deleteItem(id);
        return tag;
    }
}

 

applicationContext-dao.xml

applicationContext.xml    进行相应配置

manageList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/common/header.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>Insert title here</title>
<script src="${ctx}/scripts/validate.js"></script>
<style type="text/css"> 
html,body{height:99%; } 
#item_list{ height:100%} 
.fieldtd{
    font-size: 12;
}
</style> 
<script type="text/javascript">
// 状态值格式化
function stateFormatter(value){
    if(value==0){
        return "<a style='color:red'><b>未立项</b></a>";
    }else if(value==1){
        return "<a style='color:green'><b>已立项</b></a>";
    }
}

// 超链接格式化
function filePathFormatter(value){
    return "<a href='"+value+"'>"+value+"</a>";
}

// 打开项目添加窗口
function openAdd(){
    document.getElementById("addItem").reset();
    $('#d2').dialog('open');
}

// 保存项目
function saveItem(){
    if($("#addItem").form('validate')){    
         var da = $("#addItem").serialize();
        $.post("addItem",da,function(mes){
            if(mes=="true"){
                $('#d2').dialog('close');
                $("#item_list").datagrid("reload");
            }else{
                $.messager.alert('提示','保存失败!','error');
            }
        });
    }
}


// 编辑项目
function editItem(){
    var item = $("#item_list").datagrid("getSelected");
    if(item){
        $('#d2').dialog('open');
        $.post("getItem/"+item.id,"",function(mes){
            $("#id").val(mes.id);
            $("#itemNumber").val(mes.itemNumber);
            $("#startTime").val(mes.startTime);
            $("#manager").val(mes.manager);
            $("#tel").val(mes.tel);
            $("#inverstment").val(mes.inverstment);
            $("#filepath").val(mes.filepath);
            $("#description").val(mes.description);
            
            // 是否立项状态
            var valid=mes.isOpen;
            if(valid=="0"){
                document.getElementsByName("isOpen")[1].checked="checked";
            }else{
                document.getElementsByName("isOpen")[0].checked="checked";
            }
        });
    }
}

// 删除项目
function deleteItem(){
    var item = $("#item_list").datagrid("getSelected");
    if(item){
        $.messager.confirm('确认?', "确定删除这条项目吗", function(r){
            if (r){
                $.post("deleteItem/"+item.id,"",function(mes){
                    if(mes){
                        deleteRow(item);
                    }
                });
            }
        });
    }
}

// 表格中删除指定行
function deleteRow(row){
    $("#item_list").datagrid("deleteRow",$("#item_list").datagrid("getRowIndex",row));
}

// 项目编号验证
function checkItemNumber(itemNumber){
    // 验证正整数
    if(checkPosInteger(itemNumber,"请输入正整数!")){
        // 验证长度
        var len=getStrLength(itemNumber);
        if(len!=10){
            alert("请输入10位数字!");
            return;
        }
        // 验证日期
        var yyyy=itemNumber.substr(0,4);
        var mm=itemNumber.substr(4,2);
        var dd=itemNumber.substr(6,2);
        checkDate(yyyy+'-'+mm+'-'+dd,"前8位请输入类似20120102格式!");
    }
}

// 查看项目描述
function desFormatter(value){
    return "<input type='button' value='查看项目描述' onClick='descView(\""+value+"\")'/>";
}

// 打开项目描述窗口
function descView(value){
    $('#d3').dialog('open');
    $("#description2").val(value);
}
</script>
</head>
<body>
     <table id="item_list"  class="easyui-datagrid" fit="true" style="height: 100%" pagination="true" pageList=[15,20,30,40] 
            title="项目列表" singleSelect="true" toolbar="#tools" url="getAllItem" idField="id">
        <thead>
            <tr>
                <th field="id" align="center"  width="80" hidden=true></th>
                <th field="itemNumber" align="center"  width="100">项目编号</th>
                <th field="startTime" align="center"  width="120"  >项目开始时间    </th>
                <th field="isOpen" align="center"  width="80" formatter="stateFormatter">是否立项</th>
                <th field="manager" align="center"  width="100" >项目经理姓名</th>
                <th field="tel" align="center" width="100" >项目经理电话</th>
                <th field="inverstment" align="center"  width="100">项目投资额</th>
                <th field="filepath" align="center"  width="150" formatter="filePathFormatter">项目资料路径</th>
                <th field="description" align="center"  width="150" formatter="desFormatter">项目描述</th>
            </tr>
        </thead>
    </table>
    <!-- 工具栏  -->
    <div id="tools">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="openAdd();">添加项目</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editItem();">修改项目</a> 
        <a href="#" class="easyui-linkbutton" iconCls="icon-no" plain="true" onclick="javascript:deleteItem()">删除项目</a>
    </div>
    <!-- 新增表单  -->
    <div id="d2" class="easyui-dialog" title="项目信息" modal=true resizable=false inline=false closed=true
        style="width: 800px; height: 400px;  padding: 10px;"
        toolbar="#dlg-toolbar" resizable="true">
            <form name="addItem" id="addItem">
            <input type="hidden" id="id" name="id"> 
            <fieldset style="width: 97%">
                <legend>项目信息</legend>
                <table width=100% id="addmenu">
                <tr>
                    <td class="fieldtd" style="width: 150px">项目编号:</td>
                    <td>
                        <input name="itemNumber" id="itemNumber" class="easyui-validatebox" required="true" onblur="javascript:checkItemNumber(this.value);"/>
                    </td>
                    <td class="fieldtd" style="width: 150px">项目开始时间:</td>
                    <td>
                        <input name="startTime" class="Wdate" readonly="readonly" id="startTime" onClick="WdatePicker({dateFmt:'yyyy-MM-dd'})"/>
                    </td>
                </tr>
                <tr>
                    <td class="fieldtd">是否立项:</td>
                    <td>
                        <span style="margin-left: 10px;"><input type="radio" name="isOpen" value="1" checked="checked">是</span>
                        <span style="margin-left: 10px;"><input type="radio"  name="isOpen" value="0" >否</span>
                    </td>
                    <td class="fieldtd">项目经理姓名:</td>
                    <td>
                        <input name="manager" id="manager" class="easyui-validatebox" required="true" onblur="javascript:checkStrLength(this.value,50,'姓名超长');"/>
                    </td>
                </tr>    
                <tr>
                    <td class="fieldtd" >项目经理手机:</td>
                    <td>
                        <input name="tel" id="tel" class="easyui-validatebox" required="true" onblur="javascript:checkTelPhone(this.value,'手机号码不合法');"/>
                    </td>
                    <td class="fieldtd" >项目投资额:</td>
                    <td>
                        <input name="inverstment" id="inverstment" class="easyui-validatebox" required="true" onblur="javascript:checkPosFloat(this.value,'投资额数据不合法!');"/>
                    </td>
                </tr>
                <tr>
                    <td class="fieldtd" >项目资料路径:</td>
                    <td colspan="3">
                        <input name="filepath" id="filepath" style="width: 200"/>
                    </td>
                </tr>    
                <tr>
                    <td class="fieldtd" valign="top">项目描述:</td>
                    <td colspan="3">
                        <textarea rows="10" cols="62" name="description" id="description"></textarea>
                    </td>
                </tr>
            </table>
            </fieldset>
            </form>
        </div>
        
        <div id="dlg-toolbar" style="padding: 2px; padding-left: 10px">
            <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true"
                onclick="javascript:saveItem()">保存</a>
                    <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true"
                onclick="$('#d2').dialog('close')">关闭</a>
        </div>
        <script src="${ctx}/scripts/My97DatePicker/WdatePicker.js"></script>
        
        
        <!-- 查看项目描述  -->
        <div id="d3" class="easyui-dialog" title="查看项目描述" modal=true resizable=false inline=false closed=true
        style="width: 600px; height: 400px;  padding: 10px;"  resizable="true">
            <fieldset style="width: 97%">
                <legend>项目描述信息</legend>
                <table width=100%>            
                    <tr>
                        <td>
                            <textarea rows="20" cols="62" name="description2" id="description2" readonly="readonly"></textarea>
                        </td>
                    </tr>
                </table>
            </fieldset>
        </div>
</body>
</html>

 

 

posted on 2012-12-19 14:09  曹锋  阅读(266)  评论(0编辑  收藏  举报

导航