SpringMVC整合Hibernate实现增删改查之按条件查询
更多精彩文章欢迎关注公众号“Java之康庄大道”
首先我贴出我项目的结构,只完成了条件查询的相关代码,增删改没有写。
1.新建一个动态Web工程,导入相应jar包,编写web.xml配置文件
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
2.配置springmvc.xml
<!-- 配置自动扫描的包 --> <context:component-scan base-package="com.tideway.springmvc"></context:component-scan> <mvc:annotation-driven/> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/"></property> <property name="suffix" value=".jsp"></property> </bean>
hibernate配置文件:hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!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="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping class="com.tideway.springmvc.entity.User"/> </session-factory> </hibernate-configuration>
配置数据源,连接池c3p0, spring-common.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/attendance" /> <property name="user" value="root" /> <property name="password" value="密码" /> </bean> <!-- 配置SessionFactory 通过spring提供的LocalSessionFactoryBean进行配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 配置数据源 --> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean> <!-- 配置一个事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 添加一个通知取别名,然后决定管理哪一个事务管理器,***只是查询的话用不到事物 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.tideway.springmvc.service.*.*(..))" id="txPointcut" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> </beans>
3.创建实体类User.java
package com.tideway.springmvc.entity; 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 org.hibernate.annotations.GenericGenerator; @Entity @Table(name="t_attendance") public class User { private int id; private int enID; private String name; private Date datetime; @Id @GenericGenerator(name="id",strategy="identity") @GeneratedValue(generator="id") @Column(name="id",unique=true,nullable=false) public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name="EnID") public int getEnID() { return enID; } public void setEnID(int enID) { this.enID = enID; } @Column(name="Name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="DateTime") public Date getDatetime() { return datetime; } public void setDatetime(Date datetime) { this.datetime = datetime; } }
4.dao层接口
package com.tideway.springmvc.dao; import java.util.List; import com.tideway.springmvc.entity.User; public interface UserDao { /** * dao层接口 * 查询打卡记录 * @param EnID 工号 * @param dateafter 起止日期 * @param datebefore 截至日期 * @return */ public List<User> getUser(String EnID,String dateafter,String datebefore); }
5.dao层接口实现类
package com.tideway.springmvc.daoimpl; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tideway.springmvc.dao.UserDao; import com.tideway.springmvc.entity.User; //@Repository用于标注数据访问组件,即DAO组件 @Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; /** * 查询dao层接口实现类 * 进行动态拼接查询,拼接hql语句进行多条件查询 */ public List<User> getUser(String EnID, String dateafter, String datebefore) { String hql = "from User where 1=1"; if(EnID!=null&&!("").equals(EnID)){ hql=hql+" and EnID='"+EnID+"'"; } if(dateafter!=null&&!("").equals(dateafter)){ hql=hql+" and datetime>='"+dateafter+"'"; } if(datebefore!=null&&!("").equals(datebefore)){ hql=hql+" and datetime<='"+datebefore+"'"; } Query query = sessionFactory.getCurrentSession().createQuery(hql); List<User> list=query.list(); return list; } }
6.service层接口
package com.tideway.springmvc.service; import java.util.List; import com.tideway.springmvc.entity.User; public interface UserService { /** * 查询的Service层接口 * @param EnID 工号 * @param dateafter 起止日期 * @param datebefore 截至日期 * @return */ public List<User> getUser(String EnID,String dateafter,String datebefore); }
7.service层接口实现类
package com.tideway.springmvc.serviceimpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tideway.springmvc.dao.UserDao; import com.tideway.springmvc.entity.User; import com.tideway.springmvc.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; /** * 查询Service层接口实现类 */ public List<User> getUser(String EnID,String dateafter, String datebefore){ return userDao.getUser(EnID, dateafter, datebefore); } }
8.controller层
package com.tideway.springmvc.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.tideway.springmvc.entity.User; import com.tideway.springmvc.service.UserService; @Controller public class UserController { @Autowired private UserService userService; /** * 控制器 * @param EnID 工号 * @param dateafter 起止日期 * @param datebefore 截至日期 * @param model 返回的数据 * @return */ @RequestMapping(value="/user/getuser.do",method=RequestMethod.GET) public String getUser(String EnID,String dateafter, String datebefore,Model model){ try { List<User> list=new ArrayList<User>(); list=userService.getUser(EnID, dateafter, datebefore); model.addAttribute("lists", list); // System.out.println("list.size="+list.size()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "list"; } }
9.index.jsp查询条件表单提交
<body> <form action="/SpringMVC04/user/getuser.do"> 工号:<input type="text" name="EnID" /> 起止日期:<input type="date"name="dateafter" /> 截止日期:<input type="date"name="datebefore" /> <input type="submit" value="查询" /> </form> </body>
10.显示查询结果页面list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table border="1" style="width: 50%"> <tr> <th>ID</th> <th>工号</th> <th>名字</th> <th>签到时间</th> <th>操作</th> </tr> <c:forEach var="item" items="${lists}"> <tr> <td>${item.id}</td> <td>${item.enID}</td> <td>${item.name}</td> <td>${item.datetime}</td> <td><a href="">编辑</a></td> </tr> </c:forEach> </table> </body> </html>