DAO:spring hibernateTemplate
been的xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<!-- 此处的catalog="test"属性要删掉,不然会报sql语法错误 -->
<class name="com.forlink.been.User" table="user" >
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="userName" type="string">
<column name="userName" length="50" not-null="true"/>
</property>
<property name="passWord" type="string">
<column name="passWord" length="50" />
</property>
<property name="email" type="string">
<column name="email" length="50" />
</property>
<property name="address" type="string">
<column name="address" length="50" />
</property>
<property name="cellPhone" type="string">
<column name="cellPhone" length="50" />
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ww</property>
<property name="connection.username">root</property>
<property name="connection.password">***</property>
<property name="connection.isolation">2</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- <property name="hibernate.hbm2ddl.auto">create</property> -->
<property name="connection.autocommit">true</property>
<property name="myeclipse.connection.profile">
com.mysql.jdbc.Driver
</property>
<mapping resource="com/been/user.hbm.xml" />
</session-factory>
</hibernate-configuration>
public class DaoImpl extends HibernateDaoSupport implements Dao
{public List findPageByQuery(final String queryString,
final Object[] parameters, final PageInfo pageInfo)
{
return (List) getHibernateTemplate().execute(new HibernateCallback()//这里使用了匿名内部类
{
public Object doInHibernate(Session session)//Spring进行事务维护 省去每次创建session和关闭session
throws HibernateException
{
Query query = session.createQuery(queryString);
if (parameters != null)
{
for (int i = 0; i < parameters.length; i++)
{
query.setParameter(i, parameters[i]);
}
}
ScrollableResults sr = query.scroll();
sr.last();
int totalCount = sr.getRowNumber();
int startIndex = (pageInfo.getPageIndex() - 1)
* pageInfo.getPageSize();
query.setMaxResults(pageInfo.getPageSize());
query.setFirstResult(startIndex);
int totalRec = totalCount + 1;
pageInfo.setTotalRec(totalRec);
int totalPage = (totalRec % pageInfo.getPageSize() == 0) ? (totalRec / pageInfo
.getPageSize())
: (totalRec / pageInfo.getPageSize()) + 1;
int[] pageNumbers = new int[totalPage];
for (int i = 0; i < totalPage; i++)
{
pageNumbers[i] = (i + 1);
}
pageInfo.setPageNumbers(pageNumbers);
pageInfo.setTotalPage(totalPage);
pageInfo.setPageSize(pageInfo.getPageSize());
pageInfo.setPageIndex(pageInfo.getPageIndex());
pageInfo.setPrePage(pageInfo.getPageIndex() - 1);
pageInfo.setNextPage(pageInfo.getPageIndex() + 1);
return query.list();
}
}, true);
}
}
使用参数说明:
final String queryString 查询的语句 from aaa as y where y.id=?
final Object[] parameters 参数数组
final PageInfo pageInfo 这个是分页的类
比如: from AAA as t where t.id=? and t.name=?
object[]a={1,haha}
//Object[] a ={s};
List li = new ArrayList();
li = di.findPageByQuery("from User as user", null, fi);
// li = di.findPageByQuery("from User a", a, fi);
service:spring依赖注入
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="mySessionFactory" />
</property>
</bean>
<bean id="userDao" class="com.forlink.dao.UserDaoImpl">
<property name="sessionFactory">
<ref bean="mySessionFactory" />
</property>
</bean>
<bean id="dao" class="com.forlink.dao.DaoImpl">
<property name="sessionFactory">
<ref bean="mySessionFactory" />
</property>
</bean>
<bean id="userService" class="com.forlink.services.UserServiceImpl"
abstract="false" lazy-init="default" autowire="default"
dependency-check="default">
<property name="userDaoImpl">
<ref bean="userDao" />
</property>
</bean>
<bean id="PageService" class="com.forlink.services.PageService"
abstract="false" lazy-init="default" autowire="default"
dependency-check="default">
<property name="dao">
<ref bean="dao" />
</property>
</bean>
<bean name="/login" class="com.forlink.struts.UserLogin">
<property name="userServiceImpl">
<ref bean="userService" />
</property>
</bean>
<bean name="/page" class="com.forlink.struts.PageAction">
<property name="ps">
<ref bean="PageService" />
</property>
</bean>
<!--<bean id="userService2"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="myTransactionManager" />
</property>
<property name="target">
<ref bean="userService" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
-->
</beans>
public class PageService
{
public Dao dao;
/*
* public List getUU(String mobile, PageInfo pageInfo) throws Exception {
* List list = null; if (pageInfo == null) pageInfo = new PageInfo(); try {
* list = dao .findPageByQuery( "from uuuu u where c.mobile=? and
* c.sendtype=1 and c.groupType=1 order by c.sendTime desc", new Object[] {
* mobile }, pageInfo); } catch (DataAccessException ex) {
* ex.printStackTrace(); } return list;
*/
public List getUU(PageInfo pageInfo) throws Exception
{
/*ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
dao = (DaoImpl) context.getBean("Dao");
System.out.print(dao);*/ //自己测试时候可以使用
List list = null;
if (pageInfo == null)
pageInfo = new PageInfo();
try
{
list = dao.findPageByQuery("from User u", null, pageInfo);
} catch (DataAccessException ex)
{
ex.printStackTrace();
}
return list;
}
struts :action
public class PageAction extends Action
{
public PageService ps;
public PageInfo pageInfo=new PageInfo();
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response){
System.out.println("listlistlist");
List list = new ArrayList();
try
{
//pageInfo = (PageInfo) request.getAttribute("pageInfo");
String page=request.getParameter("page");
if(page==null)
{page="1";
}
System.out.println("action...........................");
pageInfo.setPageIndex(Integer.parseInt(page));
// pageInfo.setPageIndex(Integer.parseInt(request.getParameter("Index")));
list = ps.getUU(pageInfo);
if(list.size()!=0)
{
request.setAttribute("list", list);
request.setAttribute("pageInfo", pageInfo);
}
}catch
(Exception ex)
{
ex.printStackTrace();
}
return mapping.findForward("page");
}
public PageInfo getPageInfo()
{
return pageInfo;
}
public void setPageInfo(PageInfo pageInfo)
{
this.pageInfo = pageInfo;
}
public PageService getPs()
{
return ps;
}
public void setPs(PageService ps)
{
this.ps = ps;
}
}
你可以自己写个类 把PageInfo封装进去 我做测试 懒得依赖注入
struts配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans>
<form-bean name="loginForm" type="com.forlink.struts.UserForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action path="/login" input="/login.jsp" attribute="loginForm"
name="loginForm" scope="request" validate="true">
<set-property property="cancellable" value="true" />
<forward name="main" path="/main.jsp" />
</action>
<action path="/findLog" type="com.forlink.struts.LogAction"
scope="request" parameter="findLog">
<forward name="success" path="/index.jsp"></forward>
</action>
<action path="/page" type="com.forlink.struts.PageAction"
scope="request" >
<forward name="page" path="/page.jsp"></forward>
</action>
</action-mappings>
<controller
processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />
<message-resources
parameter="com.forlink.struts.ApplicationResources" />
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml" />
</plug-in>
</struts-config>
xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
view:用了el
<%@ page contentType="text/html; charset=GBK"%>
<%@ page import="java.util.*" %>
<%@ page import="com.been.User" %>
<jsp:directive.page import="com.dao.PageInfo;"/>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<%
String nowPage ;
int total;
nowPage=request.getParameter("page");
if(nowPage==null)
{nowPage="1";
}
int curPage=Integer.parseInt(nowPage);
if((PageInfo)request.getAttribute("pageInfo") == null){
total = 1;
} else {
total = ((PageInfo)request.getAttribute("pageInfo")).getTotalPage();
}
%>
<c:forEach var="user" items="${requestScope.list}">
<tr>
<td></td>
<td>${user.userName }</td>
</tr>
</c:forEach>
<a href="${pageContext.request.contextPath }/page.do?page=1">首页</a> |
<a href="${pageContext.request.contextPath }/page.do?page=<%=curPage-1<0?1:curPage-1%>">上一页</a> |
<a href="${pageContext.request.contextPath }/page.do?page=<%=(curPage)>total?total:curPage+1%>">下一页</a> |
<a href="${pageContext.request.contextPath }/page.do?page=<%=total %>">末页</a>
当前第<%=curPage %>页 转到第 <select id="page" οnchange="window.location.href='${pageContext.request.contextPath }/page.do?page='+document.getElementById('page').value;"> <%
for(int toPage = 1; toPage<=total; toPage++) {
%>
<option value = <%=toPage%>
<%if(toPage==curPage){ %>
selected
<%} %>
>
<%=toPage %>
</option>
<%
}
%>
</select> 页
共<%=total%>页 ssss${pageInfo.pageIndex}
</body>
</html>
还有pageInfo类
public class PageInfo
{
private int totalPage = 1;
/**
* 前一页
*/
private int prePage = 1;
/**
* 下一页
*/
private int nextPage = 1;
/**
* 总记录数
*/
private int totalRec = 0;
/**
* 默认每页记录数
*/
private final int defaultPageSize = 10;
/**
* 每页记录数
*/
private int pageSize = defaultPageSize;
/**
* 当前页码
*/
private int pageIndex = 1;
/**
* 全部页码,从1开始
*/
private int[] pageNumbers;
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex > 0 ? pageIndex : 1;
}
public int getNextPage() {
return nextPage;
}
public void setNextPage(int nextPage) {
this.nextPage = nextPage > this.totalPage ? this.totalPage : nextPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize > 0 ? pageSize : 10;
}
public int getPrePage() {
return prePage;
}
public void setPrePage(int prePage) {
this.prePage = prePage < 1 ? 1 : prePage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage > 0 ? totalPage : 1;
}
public int getTotalRec() {
return totalRec;
}
public void setTotalRec(int totalRec) {
this.totalRec = totalRec > -1 ? totalRec : 0;
}
public int[] getPageNumbers() {
return pageNumbers;
}
public void setPageNumbers(int[] pageNumbers) {
this.pageNumbers = pageNumbers;
}
}
虽然分页是很基础的 但自己写一遍还是需要细心 不然会很多BUG
起码需要你把环境搭建 自己没有利用pageinfo的total这些 属性 就是想页面自己写写
总结over