springmvc4+spring4+hibernate4注解开发,分页查询,表头排序,多条件模糊查询,查询自动补全功能

一、数据库

create table if not exists t_student(
student_id int primary key not null auto_increment,
student_name varchar(30),
student_age int ,
student_address varchar(100),
student_qq varchar(20)
) engine = InnoDB default charset = utf8;

insert into t_student values(null,'aaa',21,'China','931391200');
insert into t_student values(null,'bbb',12,'shanghai','931391221');
insert into t_student values(null,'ccc',32,'guangzhou','931391212');
insert into t_student values(null,'ddd',14,'shenzhou','93139122');
insert into t_student values(null,'eee',15,'henan','931391243');
insert into t_student values(null,'fff',17,'zhengzhou','931391214');
insert into t_student values(null,'ggg',24,'taiyuan','931391221');
insert into t_student values(null,'hhh',22,'beijing','93139127');
insert into t_student values(null,'kkk',32,'jinan','93139126');
insert into t_student values(null,'jjj',21,'dingyuan','93139123');
insert into t_student values(null,'rrr',18,'dasong','93139121');
insert into t_student values(null,'eqq',31,'yuangu','93139128');
insert into t_student values(null,'sss',19,'tangshan','9313912112');
insert into t_student values(null,'iii',25,'tangchao','9313912113');
insert into t_student values(null,'lll',27,'niboer','9313912114');
insert into t_student values(null,'yyy',26,'bajisitan','9313912115');
insert into t_student values(null,'ttt',29,'meiguo','9313912116');
insert into t_student values(null,"中国好歌曲",3,'lundun','93139121122');
insert into t_student values(null,'中国好声音',23,'lundun','93139121122');
insert into t_student values(null,'中国好舞蹈',23,'lundun','93139121122');
insert into t_student values(null,'中国之声',23,'lundun','93139121122');
insert into t_student values(null,'中国演说家',23,'lundun','93139121122');
insert into t_student values(null,'中国春节晚会',23,'lundun','93139121122');
二、实体类

      2.1数据库实体类

package com.h3c.zgc.user.entity;

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

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="t_student",catalog="itac")
public class Student {
	@Id  
	@GenericGenerator(name="generator",strategy="increment")  
	@GeneratedValue(generator="generator")  
	@Column(name="student_id",unique=true,nullable=false)
	private Integer studentId;
	@Column(name="student_name")
	private String studentName;
	@Column(name="student_age")
	private Integer studentAge;
	@Column(name="student_address")
	private String studentAddress;
	@Column(name="student_qq")
	private String studentQQ;
	
    //getter setter toStriung
}
2.2分页实体类

package com.h3c.zgc.user.entity;

import java.util.ArrayList;
import java.util.List;

public class Page {

	private int currentPageNum = 1;// 当前第几页(默认第一页),---主要用于传递到前台显示  
    private int totalPageNum;// 总页数  
    private int totalCount;// 总记录数  
    private int perPageSize = 5;// 每页显示的记录条数(默认5条)  
  
    private List entitys = new ArrayList();// 记录当前页中的数据条目  
  
    // 所有参数都进行修改  
  
    public Page(){}  
    public Page(int currentPageNum, int totalCount, int perPageSize,  
            List entitys) {  
        this.totalCount = totalCount;  
        this.perPageSize = perPageSize;  
        this.totalPageNum = totalCount % perPageSize == 0 ? totalCount  
                / perPageSize : totalCount / perPageSize + 1;  
        this.entitys = entitys;  
        this.currentPageNum = currentPageNum<1?1:(currentPageNum>totalPageNum?totalPageNum:currentPageNum);//如果当前页小于第一页,则停留在第一页  
    }  
  
    // 使用默认的当前页和每页显示记录条数  
    public Page( int totalCount, List entitys) {  
        this.totalCount = totalCount;  
        this.totalPageNum = totalCount % perPageSize == 0 ? totalCount  
                / perPageSize : totalCount / perPageSize + 1;  
        this.entitys = entitys;  
        this.currentPageNum = currentPageNum<1?1:(currentPageNum>totalPageNum?totalPageNum:currentPageNum);//如果当前页小于第一页,则停留在第一页  
    }  
  
    public int getCurrentPageNum() {  
        return currentPageNum;  
    }  
  
    public void setCurrentPageNum(int currentPageNum) {  
        this.currentPageNum = currentPageNum<1?1:(currentPageNum>totalPageNum?totalPageNum:currentPageNum);//如果当前页小于第一页,则停留在第一页  
    }  
  
    public int getTotalPageNum() {  
        return totalPageNum;  
    }  
  
    public void setTotalPageNum(int totalPageNum) {  
        this.totalPageNum = totalCount % perPageSize == 0 ? totalCount  
                / perPageSize : totalCount / perPageSize + 1;  
    }  
  
    public int getTotalCount() {  
        return totalCount;  
    }  
  
    public void setTotalCount(int totalCount) {  
        this.totalCount = totalCount;  
    }  
  
    public int getPerPageSize() {  
        return perPageSize;  
    }  
  
    public void setPerPageSize(int perPageSize) {  
        this.perPageSize = perPageSize;  
    }  
  
    public List getEntitys() {  
        return entitys;  
    }  
  
    public void setEntitys(List entitys) {  
        this.entitys = entitys;  
    }  
  
    @Override  
    public String toString() {  
        return "PageUtil [currentPageNum=" + currentPageNum + ", totalPageNum="  
                + totalPageNum + ", totalCount=" + totalCount  
                + ", perPageSize=" + perPageSize + ", entitys=" + entitys + "]";  
    }  
}
2.3接受查询参数的vo

package com.h3c.zgc.user.entity;

import javax.persistence.Column;

public class StudentView {

	private Integer studentId;
	private String studentName;
	private Integer studentAge;
	private String studentAddress;
	private String studentQQ;
	
	//getter setter toString
}
2.4接收分页数据,向前台传递表头排序的vo

package com.h3c.zgc.user.entity;

public class PageView {

    private int currentPageNum = 1;// 当前第几页(默认第一页),---主要用于传递到前台显示  
    private int totalPageNum;// 总页数  
    private int perPageSize = 5;// 每页显示的记录条数(默认5条)  
    
    private String sortRule;   //分页规则,asc升序,desc降序
    private String sortColumn;   //分页列名
	
    //getter setter toString
    
}
dao层

package com.h3c.zgc.user.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.h3c.zgc.user.entity.PageView;
import com.h3c.zgc.user.entity.Student;
import com.h3c.zgc.user.entity.StudentView;

@Repository
public class StudentDao extends HibernateDaoSupport{
	@Resource
	private void set(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
	
	public void insertStudent(Student student){
		this.getHibernateTemplate().save(student);
	}
	
	@SuppressWarnings("unchecked")
	public List getStudents(final PageView pv,StudentView sv){
		final String hql = this.getHql(sv, "from Student s where 1=1",pv);
		final int offset = (pv.getCurrentPageNum()-1)*pv.getPerPageSize();
		List students = this.getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				
				Query query = session.createQuery(hql);
				query.setFirstResult(offset);
				query.setMaxResults(pv.getPerPageSize());
				
				return query.list();
			}
		});
		return students;
	}
	public int getTotalCount(StudentView sv){
		String hql = this.getHql(sv, "select count(studentId) from Student s where 1=1",null);
		int count= ((Long)this.getHibernateTemplate().find(hql.toString()).iterator().next()).intValue();  
		return count;
	}
	
	private String getHql(StudentView sv, String hqlHeader,PageView pv){
		StringBuffer hql = new StringBuffer(hqlHeader);
		if(null!=sv.getStudentId()){
			hql.append( " and studentId = '"+sv.getStudentId()+"'");
		}
		if(null!=sv.getStudentName()&&""!=sv.getStudentName()){
			hql.append(" and studentName like '%"+sv.getStudentName()+"%'");
		}
		if(null!=sv.getStudentAge()){
			hql.append(" and studentAge = '"+sv.getStudentAge()+"'");
		}
		if(null!=sv.getStudentAddress()&&""!=sv.getStudentAddress()){
			hql.append(" and studentAddress like '%"+sv.getStudentAddress()+"%'");
		}
		if(null!=sv.getStudentQQ()&&""!=sv.getStudentQQ()){
			hql.append(" and studentQQ like '%"+sv.getStudentQQ()+"%'");
		}
		if(null!=pv&&null!=pv.getSortColumn()&&""!=pv.getSortColumn()){
			hql.append(" order by "+pv.getSortColumn()+" "+pv.getSortRule());
		}
		return hql.toString();
	}
	public List getStudentsByName(String studentName) {
		return (List) this.getHibernateTemplate().find("select s.studentName from Student s where s.studentName like '%"+studentName+"%'");
	}
	
	public Student getStudent(Integer studentId){
		return this.getHibernateTemplate().get(Student.class, studentId);
	}
	
}
service层

package com.h3c.zgc.user.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.h3c.zgc.user.dao.StudentDao;
import com.h3c.zgc.user.entity.PageView;
import com.h3c.zgc.user.entity.Student;
import com.h3c.zgc.user.entity.StudentView;
@Service
public class StudentService {
	@Resource
	private StudentDao studentDao;
	@Transactional
	public void insertStudent(Student student){
		this.studentDao.insertStudent(student);
	}
	public List getStudents(final PageView pv,StudentView sv){
		return this.studentDao.getStudents(pv, sv);
	}
	public int getTotalCount(StudentView sv){
		return this.studentDao.getTotalCount(sv);
	}
	public List getStudentsByName(String studentName){
		return this.studentDao.getStudentsByName(studentName);
	}
	public Student getStudent(Integer studentId){
		return this.studentDao.getStudent(studentId);
	}
}
controller层

package com.h3c.zgc.user.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.h3c.zgc.user.entity.Page;
import com.h3c.zgc.user.entity.PageView;
import com.h3c.zgc.user.entity.Student;
import com.h3c.zgc.user.entity.StudentView;
import com.h3c.zgc.user.service.StudentService;

@Controller
@Scope
public class StudentController {
	@Resource
	private StudentService studentService;
	@RequestMapping("getAllStudent")
	public String getAllStudent(PageView pv,StudentView sv,HttpServletRequest request){
		//获取总页数
		int totalCount = this.studentService.getTotalCount(sv);
		Page page = new Page(pv.getCurrentPageNum(), totalCount, 5, null);
		//如果当前页大于总页数,则将最大页数设置为当前页
		int currentNum = pv.getCurrentPageNum()>page.getTotalPageNum()?page.getTotalPageNum():pv.getCurrentPageNum();
		pv.setCurrentPageNum(currentNum);
		//获取集合
		List students = this.studentService.getStudents(pv, sv);
		page.setEntitys(students);
		request.setAttribute("page", page);//传递分页参数,
		request.setAttribute("view", sv);//封装前台查询参数
		request.setAttribute("pageView", pv);//主要是表头排序
//		map.put("sortColumn", pv.getSortColumn());
//		map.put("sortRule", pv.getSortRule());
		
		System.out.println(students);
		System.out.println(page);
		System.out.println(pv);
		System.out.println("年龄:"+sv.getStudentAge());
		return "user/userList";
	}
	@RequestMapping("getNames")
	public void getNames(String studentName,HttpServletResponse response){
		List studentNames = this.studentService.getStudentsByName(studentName);
		System.out.println(studentNames);
		Gson gson = new Gson();
		String strs = gson.toJson(studentNames);
		response.setContentType("text/html;charset=UTF-8");
		try {
			response.getWriter().write(strs);
		} catch (IOException e) {
			
		}
		System.out.println(strs);
	}
	@RequestMapping("getStudent")
	public String getStudent(Integer studentId,HttpServletRequest request){
		Student s = this.studentService.getStudent(studentId);
		request.setAttribute("s", s);
		return "user/updateStudent";
	}
}
主页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>




Insert title here



查找所有用户

student全部展示页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
   




Insert title here
  






student修改页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>




Insert title here


学生id
学生姓名
学生年龄
学生住址
学生QQ


你可能感兴趣的:(SpringMVC,Spring,Hibernate,js)