SSHDay04(BaseAction BaseDao 分页查询 表与表外键维护 查询Type接口)

修改客户的功能
1、先通过客户的主键查询出客户的详细信息,显示到修改的页面上
    要把客户的主键和上传文件的路径使用隐藏域保存起来

2、修改客户的信息
    修改表单的enctype属性(enctype="multipart/form-data")
    给edit.jsp页面添加文件上传项
    如果用户新上传了文件,删除旧的文件,上传新的文件
    如果用户没有上传新文件,正常更新

3、如果要客户和联系人配置了一对多
    在修改客户的时候,由于Customer对象中linkman的set中没有值【不然循环调用会报异常】,所以在默认修改Customer的时候,会把set集合中的Linkman的外键设置为null
    创建linkman的sql语句中,要求外键是不能为null的
        解决 一方放弃外键的维护
        <set name="linkman" inverse="true">

抽取通用的BaseDao功能
1、通过上面编写的功能,发现DAO层的代码比较固定,所以可以想办法抽取
2、代码
    //压制 去黄线
@SuppressWarnings("all")
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{
    //定义成员的属性
    private Class clazz;
    public BaseDaoImpl(){
//      System.out.println("执行了");
        //this表示的子类 c表示的就是 CustomerDaoImpl的对象
        Class c = this.getClass();
        // CustomerDaoImpl extends BaseDaoImpl<Customer> map<K,V>
        //第2步:获取到的是BaseDaoImpl<Customer>
        Type type = c.getGenericSuperclass();
        //目的:把type接口转换成子接口
        if(type instanceof ParameterizedType){
            ParameterizedType ptype = (ParameterizedType) type;
            //获取到Customer
            Type[] types = ptype.getActualTypeArguments();
            this.clazz = (Class) types[0];
        }
//      this.clazz = clazz;
    }
    /**
     * 添加
     */
    public void save(T t) {
        this.getHibernateTemplate().save(t);
    }
    /**
     * 删除
     */
    public void delete(T t) {
        this.getHibernateTemplate().delete(t);
    }
    /**
     * 修改
     */
    public void update(T t) {
        this.getHibernateTemplate().update(t);
    }
    /**
     * 通过主键查询
     */
    public T findById(Long id) {
        return (T) this.getHibernateTemplate().get(clazz, id);
    }
    /**
     * 查询所有的数据
     */
    public List<T> findAll() {
        return (List<T>) this.getHibernateTemplate().find("from "+clazz.getSimpleName());
    }
    /**
     * 分页查询
     */
    public PageBean<T> findByPage(Integer pageCode, Integer pageSize, DetachedCriteria criteria) {
        //创建分页的对象
        PageBean<T> page = new PageBean<T>();
        //一个一个设置
        page.setPageCode(pageCode);
        page.setPageSize(pageSize);
        //设置查询聚合函数,SQL已经变成了select count(*) from 
        criteria.setProjection(Projections.rowCount());
        List<Number> list = (List<Number>) this.getHibernateTemplate().findByCriteria(criteria);
        if(list != null && list.size()>0){
            int totalCount = list.get(0).intValue();
            //总记录数
            page.setTotalCount(totalCount);
        }
        //清除sql select * from xxx
        criteria.setProjection(null);

        List<T> beanList = (List<T>) this.getHibernateTemplate().findByCriteria(criteria,(pageCode-1)*pageSize,pageSize);
        //每页显示的数据
        page.setBeanList(beanList);
        return page;
    }

}

抽取BaseAction的功能
1、Action需要完成分页的代码,需要接受pageCode和pageSize的请求参数,可以编写BaseAction用来接受分页的请求参数
    //属性驱动的方式
    //当前页,默认值就1
    private Integer pageCode= 1;

    public void setPageCode(Integer pageCode) {
        if(pageCode== null){
            pageCode = 1; 
        }
        this.pageCode = pageCode;
    }
    //每页显示的数据的条数
    private Integer pageSize = 2;
    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
    public Integer getPageCode() {
        return pageCode;
    }
    public Integer getPageSize() {
        return pageSize;
    }
    /**
     * 调用值栈对象的set方法
     */
    public void setVs(String key,Object obj){
        ActionContext.getContext().getValueStack().set(key, obj);
    }
    /**
     * 调用值栈对象的push方法
     * @param obj
     */
    public void pushVs(Object obj){
        ActionContext.getContext().getValueStack().push(obj);

    }
}

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

                                                <c:forEach items="${page.beanList }" var="linkman">
                                                <TR
                                                    style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none">
                                                    <TD>${linkman.lkm_name }</TD>
                                                    <TD>${linkman.customer.cust_name }</TD>

                                                    <TD>${linkman.lkm_gender }</TD>
                                                    <TD>${linkman.lkm_phone }</TD>
                                                    <TD>${linkman.lkm_mobile }</TD>

                                                    <TD>
                                                    <a href="${pageContext.request.contextPath }/linkmanServlet?method=edit&lkmId=${linkman.lkm_id}">修改</a>
                                                    &nbsp;&nbsp;
                                                    <a href="${pageContext.request.contextPath }/linkmanServlet?method=delete&lkmId=${linkman.lkm_id}">删除</a>
                                                    </TD>
                                                </TR>                                   <TD><SPAN id=pagelink>
                                            <!-- 使用静态引入 -->
                                            <%@ include file="/jsp/page.jsp" %>
                                    </SPAN></TD>

Customer.hbm.xml

        <!-- 配置的多方 name是JavaBean属性名称 class="一方类的全路径" column="外键的名称"-->
        <many-to-one name="source" class="my.domain.Dict" column="cust_source"></many-to-one>
        <many-to-one name="industry" class="my.domain.Dict" column="cust_industry"></many-to-one>
        <many-to-one name="level" class="my.domain.Dict" column="cust_level"></many-to-one>
        <!-- 让客户放弃外键的维护的权力 -->
        <set name="linkmans" inverse="true">
            <key column="lkm_cust_id"></key>
            <one-to-many class="my.domain.Linkman"/>
        </set>
/**
 * 所有的Dao层的实现类,都可以继承BaseDaoImpl,增删改查分页方法不用再编写了
 * @author Administrator
 *
 * @param <T>
 */
//压制 去黄线
@SuppressWarnings("all")
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{
    //定义成员的属性
    private Class clazz;
    public BaseDaoImpl(){
//      System.out.println("执行了");
        //this表示的子类 c表示的就是 CustomerDaoImpl的对象
        Class c = this.getClass();
        // CustomerDaoImpl extends BaseDaoImpl<Customer> map<K,V>
        //第2步:获取到的是BaseDaoImpl<Customer>
        Type type = c.getGenericSuperclass();
        //目的:把type接口转换成子接口
        if(type instanceof ParameterizedType){
            ParameterizedType ptype = (ParameterizedType) type;
            //获取到Customer
            Type[] types = ptype.getActualTypeArguments();
            this.clazz = (Class) types[0];
        }
//      this.clazz = clazz;
    }
    /**
     * 添加
     */
    public void save(T t) {
        this.getHibernateTemplate().save(t);
    }
    /**
     * 删除
     */
    public void delete(T t) {
        this.getHibernateTemplate().delete(t);
    }
    /**
     * 修改
     */
    public void update(T t) {
        this.getHibernateTemplate().update(t);
    }
    /**
     * 通过主键查询
     */
    public T findById(Long id) {
        return (T) this.getHibernateTemplate().get(clazz, id);
    }
    /**
     * 查询所有的数据
     */
    public List<T> findAll() {
        return (List<T>) this.getHibernateTemplate().find("from "+clazz.getSimpleName());
    }
    /**
     * 分页查询
     */
    public PageBean<T> findByPage(Integer pageCode, Integer pageSize, DetachedCriteria criteria) {
        //创建分页的对象
        PageBean<T> page = new PageBean<T>();
        //一个一个设置
        page.setPageCode(pageCode);
        page.setPageSize(pageSize);
        //设置查询聚合函数,SQL已经变成了select count(*) from 
        criteria.setProjection(Projections.rowCount());
        List<Number> list = (List<Number>) this.getHibernateTemplate().findByCriteria(criteria);
        if(list != null && list.size()>0){
            int totalCount = list.get(0).intValue();
            //总记录数
            page.setTotalCount(totalCount);
        }
        //清除sql select * from xxx
        criteria.setProjection(null);

        List<T> beanList = (List<T>) this.getHibernateTemplate().findByCriteria(criteria,(pageCode-1)*pageSize,pageSize);
        //每页显示的数据
        page.setBeanList(beanList);
        return page;
    }

}
/**
 * Action的父类
 * @author Administrator
 *
 */
public class BaseAction extends ActionSupport{

    private static final long serialVersionUID = 6121625148251505151L; 
    //属性驱动的方式
    //当前页,默认值就1
    private Integer pageCode= 1;

    public void setPageCode(Integer pageCode) {
        if(pageCode== null){
            pageCode = 1; 
        }
        this.pageCode = pageCode;
    }
    //每页显示的数据的条数
    private Integer pageSize = 2;
    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
    public Integer getPageCode() {
        return pageCode;
    }
    public Integer getPageSize() {
        return pageSize;
    }
    /**
     * 调用值栈对象的set方法
     */
    public void setVs(String key,Object obj){
        ActionContext.getContext().getValueStack().set(key, obj);
    }
    /**
     * 调用值栈对象的push方法
     * @param obj
     */
    public void pushVs(Object obj){
        ActionContext.getContext().getValueStack().push(obj);

    }
}
public class CustomerAction  extends ActionSupport implements ModelDriven<Customer>{

    private static final long serialVersionUID = 5420567636614077045L;
    //需要手动new 和返回对象
    private Customer customer = new Customer();

    //model是CustomerAction类的属性
    public Customer getModel() {
        return customer;
    }
    //提供service的成员属性,提供set方法
    private CustomerService customerService;
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }


    /**
     * 保存客户的方法
     * @return
     */
    public String add(){
        System.out.println("web层:保存");
        /*//web工厂
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
        CustomerService service = (CustomerService) context.getBean("customerService");
//      System.out.println(customer);*/
        customerService.save(customer);

        return NONE;
    }
    //属性驱动的方式
    //当前页,默认值就1
    private Integer pageCode= 1;

    public void setPageCode(Integer pageCode) {
        if(pageCode== null){
            pageCode = 1; 
        }
        this.pageCode = pageCode;
    }
    //每页显示的数据的条数
    private Integer pageSize = 2;
    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }


    /**
     * 分页的查询方法
     * @return
     */
    public String findByPage(){
        //调用service业务层
        DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
        //拼接查询的条件
        String cust_name = customer.getCust_name();
        if(cust_name !=null && !cust_name.trim().isEmpty()){
            //说明,客户的名称输入值了
            criteria.add(Restrictions.like("cust_name", "%"+cust_name+"%"));
        }
        //拼接客户级别
        Dict level = customer.getLevel();
        if(level!=null && !level.getDict_id().trim().isEmpty()){
            //说明,客户的级别肯定选择了一个
            criteria.add(Restrictions.eq("level.dict_id", level.getDict_id()));
        }
        Dict source = customer.getSource();
        if(source!=null && !source.getDict_id().trim().isEmpty()){
            //说明,客户的级别肯定选择了一个
            criteria.add(Restrictions.eq("source.dict_id", source.getDict_id()));
        }

        //查询
        PageBean<Customer> page = customerService.findByPage(pageCode,pageSize,criteria);
        //压栈
        ValueStack vs = ActionContext.getContext().getValueStack();
        //栈顶是map<"page",page对象>
        vs.set("page", page);
        return "page";
    }
    /**
     * 初始化到添加的页面
     * @return
     */
    public String initAddUI(){
        return "initAddUI";
    }
    /**
     * 文件的上传,需要在CustomerAction类中定义成员的属性,命名是有规则的
     * private File upload;//表示要上传的文件
     * private String uoloadFileName;表示上传文件的名称(没有中文乱码)
     * private String uploadContentType; 表示上传文件的MIME类型
     * 提供set方法,拦截器就注入值了
     */
    //要上传的文件
    private File upload;
    //文件的名称
    private String uploadFileName;
    //文件的MIME的类型
    private String uploadContentType; 


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    /**
     * 保存客户的方法
     * @return
     * @throws IOException 
     */
    public String save() throws IOException{
        //文件的上传
        if(uploadFileName!=null){
            //打印
            System.out.println("文件名称:"+uploadFileName);
            System.out.println("文件类型"+uploadContentType);
            //处理文件的名称
            String uuidName = UploadUtils.getUUIDName(uploadFileName);
            /*把文件上传到D:\apache-tomcat-8.5.30\webappsupload;*/
            String path="D:\\apache-tomcat-8.5.30\\webapps\\upload\\";
            //创建file对象
            File file = new File(path+uuidName);
            //简单方式
            FileUtils.copyFile(upload, file);
            //把上传的文件的路径,保存到客户表中
            customer.setFilepath(path+uuidName);
        }
        //保存用户成功了
        customerService.save(customer);
        return "save";
    }
    /**
     * 删除客户
     * @return
     */
    public String delete(){
        //删除客户,获取客户的信息,上传文件的路径
        customer = customerService.findById(customer.getCust_id());
        //获取上传文件的连接
        String filepath = customer.getFilepath();
        //删除客户
        customerService.delete(customer);
        //删除文件
        File file = new File(filepath);
        if(file.exists()){
            file.delete();
        }
        return "delete";
    }
    /**
     * 跳转到初始修改的页面
     * @return
     */
    public String initUpdate(){
        //默认customer压栈的了,Action默认压栈,model是Action类的书写 getModel(返回Customer对象,
        customer =  customerService.findById(customer.getCust_id());
        //压栈
        return "initUpdate";
    }
    /**
     * 修改客户的功能
     * @return
     * @throws IOException 
     */
    public String update() throws IOException{
        //判断,客户上传了新的图片
        if(uploadFileName !=null ){
            //先删除旧的图片
            String oldFilepath = customer.getFilepath();
            if(oldFilepath!= null && !oldFilepath.trim().isEmpty()){
                //说明,旧的路径存在,删除图片
                File f = new File(oldFilepath);
                f.delete();
            }
            //上传新的图片
            //先处理文件的名称的问题
            String uuidName = UploadUtils.getUUIDName(uploadFileName);
            String path="D:\\apache-tomcat-8.5.30\\webapps\\upload\\";
            File file = new File(path+uuidName);
            FileUtils.copyFile(upload, file);
            //把客户新图片的连接更新到数据库中
            customer.setFilepath(path+uuidName);
        }
        //更新客户的信息
        customerService.update(customer);
        return "update";
    }
    /**
     * 查询所有的客户
     * @return
     */
    public String findAll(){
        List<Customer> list = customerService.findAll();
        //转换成json
        String jsonString = FastJsonUtil.toJSONString(list);
        HttpServletResponse response = ServletActionContext.getResponse();
        FastJsonUtil.write_json(response, jsonString);
        return NONE;
    }
}

猜你喜欢

转载自blog.csdn.net/civilizationV/article/details/80018467