首页 > 代码库 > 基于Struts2+Hibernate的Criteria多条件查询

基于Struts2+Hibernate的Criteria多条件查询

Hibernate 定义了CriteriaSpecification接口规范用来完成面向对象的条件查询,Criteria 和 DetachedCriteria 就是CriteriaSpecification的子接口。

在进行本篇的内容之前,我们先来大致说一说Criteria 和 DetachedCriteria 的主要区别:

Criteria 和 DetachedCriteria 的创建的形式不一样, Criteria 是在线的,所以它是由 Hibernate Session 进行创建的;而 DetachedCriteria 是离线的,创建时无需 Session。

有了这个认识,接下来的两篇内容就好理解了,而这一篇我们就先从 Criteria 说起。

一、导jar包

c3p0-0.9.1.jar

commons-collections-3.1.jar

commons-io-2.0.1.jar

commons-lang3-3.1.jar

commons-logging-1.1.3.jar

freemarker-2.3.19.jar

hibernate3.jar

hibernate-jpa-2.0-api-1.0.1.Final.jar

javassist-3.12.0.GA.jar

jta-1.1.jar

mysql-connector-java-5.0.8-bin.jar

struts2-core-2.3.15.3.jar

xwork-core-2.3.15.3.jar

二、web.xml配置Struts2核心过滤器

技术分享
  1 <filter>
  2     <filter-name>struts2</filter-name>
  3     <filter-class>
  4          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  5     </filter-class>
  6   </filter>
  7 
  8   <filter-mapping>
  9     <filter-name>struts2</filter-name>
 10     <url-pattern>/*</url-pattern>
 11   </filter-mapping>XML Code
XML Code

三、Jsp表单查询页

技术分享
  1 <form id="Form1" name="Form1" action="queryUser.action" method="post">
  2 	<table cellSpacing="1" cellPadding="0" width="100%" align="center" bgColor="#f5fafe" 
  3           border="0">
  4 	     <TBODY>
  5 	          <tr>
  6 	               <td class="ta_01" align="center" bgColor="#afd1f3">
  7 		      <strong>查 询 条 件</strong>
  8 		      </td>
  9 		 </tr>
 10 		 <tr>
 11 		      <td>
 12 			    <table cellpadding="0" cellspacing="0" border="0" 
 13                                  width="100%">
 14 				 <tr>
 15 				      <td height="22" align="center" bgColor="#f5fafe" 
 16                                             class="ta_01">用户姓名</td>
 17 				      <td class="ta_01" bgColor="#ffffff">	             
 18			               <input type="text" name="userName" size="15" value="http://www.mamicode.com/" 
 19                                             id="Form1_userName" class="bg"/></td>
 20 				      <td height="22" align="center" bgColor="#f5fafe" 
 21                                             class="ta_01">性别:</td>
 22 				      <td class="ta_01" bgColor="#ffffff">
 23 					  <select name="gender" id="sex">
 24 						<option value="http://www.mamicode.com/">--选择性别--</option>
 25 						<option value="http://www.mamicode.com/">男</option>
 26 						<option value="http://www.mamicode.com/">女</option>
 27 					  </select>
 28 				      </td>
 29 				</tr>
 30 				<tr>
 31 				      <td height="22" align="center" bgColor="#f5fafe" 
 32                                             class="ta_01">学历:</td>
 33 				      <td class="ta_01" bgColor="#ffffff">
 34					  <select name="education" id="education">
 35					         <option value="http://www.mamicode.com/">--选择学历--</option>
 36                                                    <option value="http://www.mamicode.com/博士">博士</option>
 37						<option value="http://www.mamicode.com/硕士">硕士</option>	     
 38						<option value="http://www.mamicode.com/研究生">研究生</option> 
 39						<option value="http://www.mamicode.com/本科">本科</option>
 40					         <option value="http://www.mamicode.com/专科">专科</option>
 41						<option value="http://www.mamicode.com/高中">高中</option>
 42					  </select>
 43 				      </td>
 44 				      <td height="22" align="center" bgColor="#f5fafe" 
 45                                             class="ta_01">是否上传简历</td>
 46 				      <td class="ta_01" bgColor="#ffffff">
 47			                    <select name="isUpload" id="isUpload">
 48						<option value="http://www.mamicode.com/">--请选择--</option>
 49						<option value="http://www.mamicode.com/1">有</option>
 50		                                     <option value="http://www.mamicode.com/2">无</option>
 51					  </select>
 52 				      </td>
 53 			        </tr>
 54 			        <tr>
 55 				      <td width="100" height="22" align="center" 
 56                                             bgColor="#f5fafe" class="ta_01"></td>
 57 				      <td class="ta_01" bgColor="#ffffff">
 58				           <font face="宋体" color="red"> &nbsp;</font>
 59 				      </td>
 60 				      <td align="right" bgColor="#ffffff" 
 61                                             class="ta_01"><br><br></td>
 62 				      <td align="right" bgColor="#ffffff" class="ta_01">
 63					  <button type="submit" id="search" name="search" 
 64                                                value="http://www.mamicode.com/&#26597;&#35810;"class="button_view">
 65                                                &#26597;&#35810;</button>
 66				              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 67				           <input type="reset" name="reset" 
 68                                             value="http://www.mamicode.com/&#37325;&#32622;" class="button_view"/>
 69				      </td>
 70 				</tr>
 71 			     </table>
 72 		         </td>
 73 	            </tr>
 74           </TBODY>
 75 	</table>
 76 </form>
JSP Code

四、UserBean

技术分享
  1 package com.fhcq.bean;
  2 
  3 import java.io.Serializable;
  4 
  5 public class User implements Serializable {
  6 
  7 	private Integer userID;
  8 	private String userName;
  9 	private String gender;
 10 	private String education;
 11 	private String path;
 12 	private String filename;
 13 
 14 	public Integer getUserID() {
 15 		return userID;
 16 	}
 17 	public void setUserID(Integer userID) {
 18 		this.userID = userID;
 19 	}
 20 	public String getUserName() {
 21 		return userName;
 22 	}
 23 	public void setUserName(String userName) {
 24 		this.userName = userName;
 25 	}
 26 	public String getGender() {
 27 		return gender;
 28 	}
 29 	public void setGender(String gender) {
 30 		this.gender = gender;
 31 	}
 32 	public String getEducation() {
 33 		return education;
 34 	}
 35 	public void setEducation(String education) {
 36 		this.education = education;
 37 	}
 38 	public String getPath() {
 39 		return path;
 40 	}
 41 	public void setPath(String path) {
 42 		this.path = path;
 43 	}
 44 	public String getFilename() {
 45 		return filename;
 46 	}
 47 	public void setFilename(String filename) {
 48 		this.filename = filename;
 49 	}
 50 }
 51 
UserBean Code

五、User.hbm.xml

技术分享
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <!DOCTYPE hibernate-mapping PUBLIC
  3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  5 <hibernate-mapping package="com.fhcq.bean">
  6 
  7     <!-- name是类名  如果有包就不用写全类名,否则要写。  table 表示对应的表名 。建议都要写  -->
  8     <class name="User" table="user">
  9 
 10            <!--使用Id配置主键 必须配置  -->
 11            <id name="userID" column="userID">
 12                   <!--目前照常,主键生成策略  -->
 13                   <generator class="native"></generator>
 14            </id>
 15 
 16           <property name="userName"  column="userName"></property>
 17           <property name="gender"  column="gender"></property>
 18           <property name="education"  column="education"></property>
 19           <property name="path"  column="path"></property>
 20           <property name="filename"  column="filename"></property>
 21 
 22     </class>
 23 </hibernate-mapping>
XML Code

六、hibernate.cfg.xml

技术分享
  1 <!DOCTYPE hibernate-configuration PUBLIC
  2 	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  3 	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  4 
  5 <hibernate-configuration>
  6      <session-factory name="foo">
  7 
  8 	    <!-- 配置数据库驱动 -->
  9 	    <property name="hibernate.connection.driver_class">
 10 		com.mysql.jdbc.Driver
 11 	    </property>
 12 	    <!-- 要连接数控的用户名  -->
 13 	    <property name="hibernate.connection.username">root</property>
 14 	    <!-- 密码 -->
 15 	    <property name="hibernate.connection.password">123456</property>
 16 	    <!-- 连接数据库的路径 那个服务器 那个数据库  -->
 17 	    <property name="hibernate.connection.url">
 18 		jdbc:mysql://localhost:3306/usermanager
 19 	    </property>
 20 
 21 	    <!-- 操作的时候显示操做过程中的sql语句  -->
 22 	    <property name="show_sql">true</property>
 23 	    <!-- 格式化它要显示的sql语句 -->
 24 	    <property name="format_sql">true</property>
 25 	    <!-- 是否要自动创建表  -->
 26 	    <property name="hbm2ddl.auto">update</property>
 27 	    <!-- 事务自动提交  -->
 28 	    <property name="connection.autocommit">true</property>
 29 
 30 	    <!-- 优化选项 -->
 31 	    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect	</property>
 32 	    <!-- 导入映射文件 -->
 33 	    <mapping resource="com/fhcq/bean/User.hbm.xml" />
 34 
 35      </session-factory>
 36 </hibernate-configuration>
XML Code

七、QueryUserAction

技术分享
  1 package com.fhcq.action;
  2 
  3 import java.util.List;
  4 import com.fhcq.bean.User;
  5 import com.fhcq.service.IUserService;
  6 import com.fhcq.service.impl.UserServiceImpl;
  7 import com.opensymphony.xwork2.ActionContext;
  8 import com.opensymphony.xwork2.ActionSupport;
  9 import com.opensymphony.xwork2.ModelDriven;
 10 import com.opensymphony.xwork2.util.ValueStack;
 11 
 12 public class QueryUserAction extends ActionSupport implements ModelDriven<User>{
 13 
 14 	User user= new User();
 15 	private String isUpload;
 16 	IUserService service = new UserServiceImpl();
 17 
 18 	public String queryUser(){
 19 
 20 		System.out.println("QueryUserAction queryUser() isUpload=="+isUpload);
 21 
 22 		String userName = user.getUserName();
 23 		String gender = user.getGender();
 24 		String education = user.getEducation();
 25 
 26 		List<User> users = service.queryUserByManyCondition
 27                     (userName,gender,education,isUpload);
 28 		System.out.println("QueryUserAction queryUser() users= "+users);
 29 
 30 		ActionContext context = ActionContext.getContext();
 31 		ValueStack valueStack = context.getValueStack();
 32 		valueStack.push(users);
 33 
 34 		return SUCCESS;
 35 
 36 	}
 37 
 38 	@Override
 39 	public User getModel() {
 40 		// TODO Auto-generated method stub
 41 		return user;
 42 	}
 43 
 44 	public User getUser() {
 45 		return user;
 46 	}
 47 	public void setUser(User user) {
 48 		this.user = user;
 49 	}
 50 
 51 	public String getIsUpload() {
 52 		return isUpload;
 53 	}
 54 
 55 	public void setIsUpload(String isUpload) {
 56 		this.isUpload = isUpload;
 57 	}
 58 
 59 }
Action Code

八、配置Struts.xml

技术分享
  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!DOCTYPE struts PUBLIC
  3 	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  4 	"http://struts.apache.org/dtds/struts-2.3.dtd">
  5 
  6 <struts>
  7    <!--修改struct2称为开发模式,修改配置之后会自动加载  -->
  8    <constant name="struts.devMode" value="http://www.mamicode.com/true"></constant>
  9 
 10 	<package name="package1" extends="struts-default">
 11 		<!-- 多条件查询 -->
 12 		 <action name="queryUser" class="com.fhcq.action.QueryUserAction"
 13                       method="queryUser">
 14 			<result name="success">/user/list.jsp</result>
 15 		</action>
 16 
 17 	</package>
 18 
 19 </struts>
XML Code

九、QueryUserService接口

技术分享
  1    package com.fhcq.service;
  2 
  3    import java.util.List;
  4    import com.fhcq.bean.User;
  5 
  6    public interface IUserService {
  7 
  8    	List<User> queryUserByManyCondition(String userName, String gender, String education,
  9            String isUpload);
 10 
 11    }
Service Code

十、QueryUserServiceImpl

技术分享
  1 package com.fhcq.service.impl;
  2 
  3 import java.sql.SQLException;
  4 import java.util.List;
  5 
  6 import com.fhcq.bean.User;
  7 import com.fhcq.dao.IUserDao;
  8 import com.fhcq.dao.impl.UserDaoImpl;
  9 import com.fhcq.service.IUserService;
 10 
 11 public class UserServiceImpl implements IUserService {
 12 
 13 	IUserDao dao = new UserDaoImpl();
 14 
 15 	@Override
 16 	public List<User> queryUserByManyCondition(String userName, String gender, String 
 17               education, String isUpload) {
 18 		// TODO Auto-generated method stub
 19 		List<User> queryUserByManyCondition = dao.queryUserByManyCondition
 20                       (userName,gender,education,isUpload);
 21 		return queryUserByManyCondition;
 22	}
 23 
 24 }
 25 
ServiceImpl Code

十一、QueryUserDao接口

技术分享
  1 package com.fhcq.dao;
  2 
  3 import java.sql.SQLException;
  4 import java.util.List;
  5 import com.fhcq.bean.User;
  6 
  7 public interface IUserDao {
  8 
  9 	List<User> queryUserByManyCondition(String userName, String gender, String education,
 10             String isUpload);
 11 }
 12 
Dao Code

十二、QueryUserDaoImpl

技术分享
  1   package com.fhcq.dao.impl;
  2 
  3   import java.sql.SQLException;
  4   import java.util.ArrayList;
  5   import java.util.List;
  6 
  7   import org.apache.commons.lang3.StringUtils;
  8   import org.hibernate.Criteria;
  9   import org.hibernate.Query;
 10   import org.hibernate.Session;
 11   import org.hibernate.SessionFactory;
 12   import org.hibernate.cfg.Configuration;
 13   import org.hibernate.criterion.Restrictions;
 14 
 15   import com.fhcq.bean.User;
 16   import com.fhcq.dao.IUserDao;
 17   import com.fhcq.utils.HibernateUtils;
 18 
 19   public class UserDaoImpl implements IUserDao{
 20   	@Override
 21  	public List<User> queryUserByManyCondition(String userName, String gender, String
 22              education, String isUpload) {
 23   	      // TODO Auto-generated method stub
 24 
 25   	      //如果查询页所有条件都没有填选的话,点击查询按钮转查询所有用户
 26  	      if(StringUtils.isBlank(userName) && StringUtils.isBlank(gender) &&
 27                  StringUtils.isBlank(education) && StringUtils.isBlank(isUpload)){
 28 		   
 29                  Session session = HibernateUtils.getSession();
 30 		   session.beginTransaction();
 31 		   //-----------------------------	
 32 		   Query createQuery = session.createQuery("from User");
 33 		   List<User> users = createQuery.list();
 34 		   //------------------------------
 35 		   session.getTransaction().commit();
 36 		   session.close();
 37 		   return users;
 38   	      }else{
 39                  Configuration configure = new Configuration().configure();
 40   	            SessionFactory  sessionFactory = configure.buildSessionFactory();
 41   	            Session openSession = sessionFactory.openSession();
 42   		    //------------------------------
 43 
 44   		    Criteria createCriteria = openSession.createCriteria(User.class);
 45 
 46   		    if(StringUtils.isNotBlank(userName)){
 47  			 createCriteria.add(Restrictions.like("userName", userName));
 48    		    }
 49   		    if(StringUtils.isNotBlank(gender)){
 50   			 createCriteria.add(Restrictions.eq("gender", gender));
 51    		    }
 52   		    if(StringUtils.isNotBlank(education)){
 53   			 createCriteria.add(Restrictions.eq("education", education));
 54    		    }
 55 
 56   		    if(StringUtils.isNotBlank(isUpload)){
 57 
 58   			 if("1".equals(isUpload)){
 59 
 60   			        createCriteria.add(Restrictions.isNotNull("filename"));
 61   			 }else{
 62 
 63  			        createCriteria.add(Restrictions.isNull("filename"));
 64   			 }
 65   		    }
 66 
 67  		    List list = createCriteria.list();
 68 
 69   	            //------------------------------
 70   		    openSession.close();
 71   		    sessionFactory.close();
 72   		    return list;
 73 
 74   		}
 75 	 }
 76 
 77   }
DaoImpl Code

基于Struts2+Hibernate的Criteria多条件查询