前言:当前Web项目开发的框架主流应该非Spring+SpringMVC+Hibernate莫属,不管是工作还是学习中涉及框架技术,首先是要搭建一套运行环境,虽然网上框架整合的教程很多,但我还是输出此文,一是自己总结整理可巩固理解,二是可供有需要学习的同仁参考。本着负责人的态度,本文所有内容测试通过,运行环境为JDK8+Tomcat8,Spring4.3.9,Hibernate5.2.10.
本篇文章重点关注以下问题:
- 框架配置文件的编写
- 后台Controller、Service、Dao层编写
- 在Dao层封装基本CRUD操作
- 前台页面编写
备注:本文为简明扼要,只在代码中对关键之处进行说明,有关框架的具体使用细节,可查阅相关资料,当然,自认为代码中的说明已够详细。另外,所有配置都是基于注解的方式实现。
项目结构:
1. 配置文件
1.1 web.xml
web.xml为web项目的入口,因此首先配置web.xml. 文件中配置的编码格式和session并不是必须的,但又是很常用的,所以就一并附上了。
- <?xml version=“1.0” encoding=“UTF-8”?>
- <web-app version=“3.1”
- xmlns=“http://xmlns.jcp.org/xml/ns/javaee”
- xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
- xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee
- http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd”>
- <!– 配置Spring初始化参数(配置文件位置). –>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext.xml</param-value>
- </context-param>
- <!– 配置Spring监听器. –>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!– 配置SpringMVC –>
- <servlet>
- <servlet-name>springMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/spring-mvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springMVC</servlet-name>
- <url-pattern>*.action</url-pattern>
- </servlet-mapping>
- <!– 配置编码格式. –>
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!– 配置session –>
- <filter>
- <filter-name>openSession</filter-name>
- <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>openSession</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>login.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <!-- 配置Spring初始化参数(配置文件位置). --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!-- 配置Spring监听器. --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置SpringMVC --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- 配置编码格式. --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置session --> <filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
1.2 SpringMVC配置文件
- <?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”
- xsi:schemaLocation=”http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.3.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd”>
- <!– 注解扫描包(SpringMVC只关注控制器类上的注解) –>
- <context:component-scan base-package=“com.wj.control” />
- <!– 开启注解 –>
- <mvc:annotation-driven />
- <!– 静态资源(js/image)的访问 –>
- <!– 针对SpringMVC拦截所有请求的情况下才需要配置,以防对静态资源的访问也被拦截. –>
- <!– <mvc:resources location=”/js/” mapping=”/js/**”/> –>
- <!– 定义视图解析器(此处针对Jsp) –>
- <bean id=“viewResolver” class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>
- <!– 所有URI的前缀. –>
- <property name=“prefix” value=“/jsp/”></property>
- <!– 所有URI的后缀. –>
- <property name=“suffix” value=“.jsp”></property>
- </bean>
- </beans>
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 注解扫描包(SpringMVC只关注控制器类上的注解) --> <context:component-scan base-package="com.wj.control" /> <!-- 开启注解 --> <mvc:annotation-driven /> <!-- 静态资源(js/image)的访问 --> <!-- 针对SpringMVC拦截所有请求的情况下才需要配置,以防对静态资源的访问也被拦截. --> <!-- <mvc:resources location="/js/" mapping="/js/**"/> --> <!-- 定义视图解析器(此处针对Jsp) --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 所有URI的前缀. --> <property name="prefix" value="/jsp/"></property> <!-- 所有URI的后缀. --> <property name="suffix" value=".jsp"></property> </bean> </beans>
1.3 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”
- xmlns:context=“http://www.springframework.org/schema/context”
- xmlns:tx=“http://www.springframework.org/schema/tx”
- xmlns:mvc=“http://www.springframework.org/schema/mvc”
- xsi:schemaLocation=”http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.3.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-2.0.xsd”>
- <!– 指定Spring需要扫描的包,需要Spring管理的Bean必须在此包里. –>
- <!– 当然,由SpringMVC已扫描的bean此处并不需要扫描.(可指明不需要哪些bean,此处未实现) –>
- <context:component-scan base-package=“com.wj” />
- <!– 使用annotation定义事务 –>
- <tx:annotation-driven transaction-manager=“transactionManager” />
- <!– 配置数据源 –>
- <bean id=“dataSource” class=“org.springframework.jdbc.datasource.DriverManagerDataSource” >
- <property name=“driverClassName” value=“com.mysql.jdbc.Driver”></property>
- <property name=“url” value=“jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8”></property>
- <property name=“username” value=“root”></property>
- <property name=“password” value=“root”></property>
- </bean>
- <!– 配置SessionFactory –>
- <bean id=“sessionFactory” class=“org.springframework.orm.hibernate5.LocalSessionFactoryBean”>
- <property name=“dataSource” ref=“dataSource” />
- <property name=“hibernateProperties”>
- <props>
- <!– 指定Hibernate的连接方言 –>
- <prop key=“hibernate.dialect”>org.hibernate.dialect.MySQLDialect</prop>
- <!–是否根据Hiberante映射创建数据表 –>
- <prop key=“hibernate.hbm2ddl.auto”>update</prop>
- <prop key=“hibernate.show_sql”>true</prop>
- <prop key=“hibernate.format_sql”>true</prop>
- </props>
- </property>
- <!– 指明与数据库表对应的实体类(这种特殊的类我更倾向在配置文件中指明,一目了然) –>
- <property name=“annotatedClasses”>
- <list>
- <value>com.wj.entity.User</value>
- </list>
- </property>
- </bean>
- <!– 配置一个事务管理器 –>
- <bean id=“transactionManager” class=“org.springframework.orm.hibernate5.HibernateTransactionManager”>
- <property name=“sessionFactory” ref=“sessionFactory”/>
- </bean>
- </beans>
<?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:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <!-- 指定Spring需要扫描的包,需要Spring管理的Bean必须在此包里. --> <!-- 当然,由SpringMVC已扫描的bean此处并不需要扫描.(可指明不需要哪些bean,此处未实现) --> <context:component-scan base-package="com.wj" /> <!-- 使用annotation定义事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <!-- 指定Hibernate的连接方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!--是否根据Hiberante映射创建数据表 --> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <!-- 指明与数据库表对应的实体类(这种特殊的类我更倾向在配置文件中指明,一目了然) --> <property name="annotatedClasses"> <list> <value>com.wj.entity.User</value> </list> </property> </bean> <!-- 配置一个事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans>
2. 后台Controller、Service、Dao层编写
2.1 首先定义实体类
- package com.wj.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_USER”)
- public class User {
- @Id
- @GeneratedValue(generator=“system-uuid”)
- @GenericGenerator(name = “system-uuid”,strategy=“uuid”)
- @Column(length=32)
- private String id;
- @Column(length=32)
- private String userName;
- @Column(length=32)
- private String age;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getAge() {
- return age;
- }
- public void setAge(String age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return “User [id=” + id + “, userName=” + userName + “, age=” + age + “]”;
- }
- }
package com.wj.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_USER")
public class User {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name = "system-uuid",strategy="uuid")
@Column(length=32)
private String id;
@Column(length=32)
private String userName;
@Column(length=32)
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]";
}
}
2.2 Controller层
Spring提倡的主题之一就是面向接口编程,但是Controller层我并未定义接口,因为Controller层我仅写了几个测试方法,实现CRUD,定义接口并没有太大意义。
- package com.wj.control;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import com.wj.entity.User;
- import com.wj.service.IUserService;
- @Controller // 指明当前类是控制器
- @RequestMapping(“/jsp/user”) // 根路径
- public class UserController {
- @Autowired // 以类型的方式注入(Spring有多种方式实现自动注入,但按类型注入更简单清晰)
- private IUserService userService;
- @RequestMapping(“/getAllUser.action”)
- public String getAllUser(HttpServletRequest request){
- List<User> userList = userService.getAllUser();
- request.setAttribute(”userList”, userList);
- return “user/index”;
- }
- @RequestMapping(“/getUser.action”)
- public String getUser(String id,HttpServletRequest request){
- User user = userService.getUser(id);
- request.setAttribute(”user”, user);
- return “user/editUser”;
- }
- @RequestMapping(“/toAddUser.action”)
- public String toAddUser(){
- return “user/addUser”;
- }
- @RequestMapping(“/addUser.action”)
- public String addUser(User user,HttpServletRequest request){
- userService.addUser(user);
- return “redirect:/jsp/user/getAllUser.action”;
- }
- @RequestMapping(“/delUser.action”)
- public void delUser(String id,HttpServletResponse response){
- String result = ”{\”result\”:\”error\”}”;
- if(userService.delUser(id)){
- result = ”{\”result\”:\”success\”}”;
- }
- response.setContentType(”application/json”);
- try {
- PrintWriter out = response.getWriter();
- out.write(result);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- @RequestMapping(“/updateUser”)
- public String updateUser(User user,HttpServletRequest request){
- if(userService.updateUser(user)){
- user = userService.getUser(user.getId());
- request.setAttribute(”user”, user);
- return “redirect:/jsp/user/getAllUser.action”;
- }else{
- return “user/error”;
- }
- }
- }
package com.wj.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wj.entity.User;
import com.wj.service.IUserService;
@Controller // 指明当前类是控制器
@RequestMapping("/jsp/user") // 根路径
public class UserController {
@Autowired // 以类型的方式注入(Spring有多种方式实现自动注入,但按类型注入更简单清晰)
private IUserService userService;
@RequestMapping("/getAllUser.action")
public String getAllUser(HttpServletRequest request){
List<User> userList = userService.getAllUser();
request.setAttribute("userList", userList);
return "user/index";
}
@RequestMapping("/getUser.action")
public String getUser(String id,HttpServletRequest request){
User user = userService.getUser(id);
request.setAttribute("user", user);
return "user/editUser";
}
@RequestMapping("/toAddUser.action")
public String toAddUser(){
return "user/addUser";
}
@RequestMapping("/addUser.action")
public String addUser(User user,HttpServletRequest request){
userService.addUser(user);
return "redirect:/jsp/user/getAllUser.action";
}
@RequestMapping("/delUser.action")
public void delUser(String id,HttpServletResponse response){
String result = "{\"result\":\"error\"}";
if(userService.delUser(id)){
result = "{\"result\":\"success\"}";
}
response.setContentType("application/json");
try {
PrintWriter out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("/updateUser")
public String updateUser(User user,HttpServletRequest request){
if(userService.updateUser(user)){
user = userService.getUser(user.getId());
request.setAttribute("user", user);
return "redirect:/jsp/user/getAllUser.action";
}else{
return "user/error";
}
}
}
2.3 Service层
先定义业务层的业务接口:
- package com.wj.service;
- import java.util.List;
- import com.wj.entity.User;
- public interface IUserService {
- /**
- * 根据id获取指定用户
- * @param id
- * @return
- */
- public User getUser(String id);
- /**
- * 查询所有用户
- * @return
- */
- public List<User> getAllUser();
- /**
- * 新增用户
- * @param user
- */
- public void addUser(User user);
- /**
- * 根据id删除指定用户
- * @param id
- * @return
- */
- public boolean delUser(String id);
- /**
- * 更新用户信息
- * @param user
- * @return
- */
- public boolean updateUser(User user);
- }
package com.wj.service;
import java.util.List;
import com.wj.entity.User;
public interface IUserService {
/**
* 根据id获取指定用户
* @param id
* @return
*/
public User getUser(String id);
/**
* 查询所有用户
* @return
*/
public List<User> getAllUser();
/**
* 新增用户
* @param user
*/
public void addUser(User user);
/**
* 根据id删除指定用户
* @param id
* @return
*/
public boolean delUser(String id);
/**
* 更新用户信息
* @param user
* @return
*/
public boolean updateUser(User user);
}
此样例中业务层并没有复杂业务,只是增删改查:
- package com.wj.service;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import com.wj.dao.IUserDao;
- import com.wj.entity.User;
- @Service
- public class UserService implements IUserService {
- @Autowired
- private IUserDao userDao;
- @Override
- public User getUser(String id) {
- return userDao.getUser(id);
- }
- @Override
- public List<User> getAllUser() {
- return userDao.getAllUser();
- }
- @Override
- @Transactional
- public void addUser(User user) {
- userDao.addUser(user);
- }
- @Override
- @Transactional
- public boolean delUser(String id) {
- return userDao.delUser(id);
- }
- @Override
- @Transactional
- public boolean updateUser(User user) {
- return userDao.updateUser(user);
- }
- }
package com.wj.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wj.dao.IUserDao;
import com.wj.entity.User;
@Service
public class UserService implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public User getUser(String id) {
return userDao.getUser(id);
}
@Override
public List<User> getAllUser() {
return userDao.getAllUser();
}
@Override
@Transactional
public void addUser(User user) {
userDao.addUser(user);
}
@Override
@Transactional
public boolean delUser(String id) {
return userDao.delUser(id);
}
@Override
@Transactional
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
}
2.4 Dao层
首先定义接口:
- package com.wj.dao;
- import java.util.List;
- import com.wj.entity.User;
- public interface IUserDao {
- public User getUser(String id);
- public List<User> getAllUser();
- public void addUser(User user);
- public boolean delUser(String id);
- public boolean updateUser(User user);
- }
package com.wj.dao;
import java.util.List;
import com.wj.entity.User;
public interface IUserDao {
public User getUser(String id);
public List<User> getAllUser();
public void addUser(User user);
public boolean delUser(String id);
public boolean updateUser(User user);
}
再贴上Dao层的实现:
- package com.wj.dao;
- import java.util.List;
- import org.springframework.stereotype.Repository;
- import com.wj.entity.User;
- @Repository
- public class UserDao extends BaseDao<User> implements IUserDao {
- @Override
- public User getUser(String id) {
- return get(User.class, id);
- }
- @Override
- public List<User> getAllUser() {
- return findAll(User.class);
- }
- @Override
- public void addUser(User user) {
- save(user);
- }
- @Override
- public boolean delUser(String id) {
- return delete(User.class, id);
- }
- @Override
- public boolean updateUser(User user) {
- update(user);
- return true;
- // String hql = “update User u set u.userName = ?0,u.age=?1 where u.id = ?2”;
- // Query<User> query = sessionFactory.getCurrentSession().createQuery(hql);
- // query.setParameter(0, user.getUserName());
- // query.setParameter(1, user.getAge());
- // query.setParameter(2, user.getId());
- //
- // return (query.executeUpdate() > 0);
- }
- }
package com.wj.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.wj.entity.User;
@Repository
public class UserDao extends BaseDao<User> implements IUserDao {
@Override
public User getUser(String id) {
return get(User.class, id);
}
@Override
public List<User> getAllUser() {
return findAll(User.class);
}
@Override
public void addUser(User user) {
save(user);
}
@Override
public boolean delUser(String id) {
return delete(User.class, id);
}
@Override
public boolean updateUser(User user) {
update(user);
return true;
// String hql = "update User u set u.userName = ?0,u.age=?1 where u.id = ?2";
// Query<User> query = sessionFactory.getCurrentSession().createQuery(hql);
// query.setParameter(0, user.getUserName());
// query.setParameter(1, user.getAge());
// query.setParameter(2, user.getId());
//
// return (query.executeUpdate() > 0);
}
}
仔细观察Dao层,发现CRUD操作都是基于BaseDao提供的API进行的,显得相当简便,下面贴上BaseDao的实现。
3. 在Dao层封装基本CRUD操作
首先定义CRUD操作的接口,为适配各实体类,此处引入泛型:
- package com.wj.dao;
- import java.io.Serializable;
- import java.util.List;
- public interface IBaseDao<T> {
- /**
- * 根据ID加载实体
- * @param entityClazz
- * @param id
- * @return
- */
- T get(Class<T> entityClazz , Serializable id);
- /**
- * 保存实体
- * @param entity
- * @return
- */
- Serializable save(T entity);
- /**
- * 更新实体
- * @param entity
- */
- void update(T entity);
- /**
- * 删除实体
- * @param entity
- */
- void delete(T entity);
- /**
- * 根据ID删除实体
- * @param entityClazz
- * @param id
- */
- boolean delete(Class<T> entityClazz , Serializable id);
- /**
- * 获取所有实体
- * @param entityClazz
- * @return
- */
- List<T> findAll(Class<T> entityClazz);
- /**
- * 获取实体总数
- * @param entityClazz
- * @return
- */
- long findCount(Class<T> entityClazz);
- }
package com.wj.dao;
import java.io.Serializable;
import java.util.List;
public interface IBaseDao<T> {
/**
* 根据ID加载实体
* @param entityClazz
* @param id
* @return
*/
T get(Class<T> entityClazz , Serializable id);
/**
* 保存实体
* @param entity
* @return
*/
Serializable save(T entity);
/**
* 更新实体
* @param entity
*/
void update(T entity);
/**
* 删除实体
* @param entity
*/
void delete(T entity);
/**
* 根据ID删除实体
* @param entityClazz
* @param id
*/
boolean delete(Class<T> entityClazz , Serializable id);
/**
* 获取所有实体
* @param entityClazz
* @return
*/
List<T> findAll(Class<T> entityClazz);
/**
* 获取实体总数
* @param entityClazz
* @return
*/
long findCount(Class<T> entityClazz);
}
CRUD的具体实现如下:
- package com.wj.dao;
- import java.io.Serializable;
- import java.util.List;
- import org.hibernate.SessionFactory;
- import org.hibernate.query.Query;
- import org.springframework.beans.factory.annotation.Autowired;
- public class BaseDao<T> implements IBaseDao<T> {
- @Autowired
- protected SessionFactory sessionFactory;
- @Override
- public T get(Class<T> entityClazz, Serializable id) {
- return sessionFactory.getCurrentSession().get(entityClazz, id);
- }
- @Override
- public Serializable save(T entity) {
- return sessionFactory.getCurrentSession().save(entity);
- }
- @Override
- public void update(T entity) {
- sessionFactory.getCurrentSession().saveOrUpdate(entity);
- }
- @Override
- public void delete(T entity) {
- sessionFactory.getCurrentSession().delete(entity);
- }
- @Override
- @SuppressWarnings(“unchecked”)
- public boolean delete(Class<T> entityClazz, Serializable id) {
- String hql = ”delete ” + entityClazz.getSimpleName() + “ en where en.id = ?0”;
- Query<T> query = sessionFactory.getCurrentSession()
- .createQuery(hql)
- .setParameter(”0”, id);
- return (query.executeUpdate() > 0);
- }
- @Override
- public List<T> findAll(Class<T> entityClazz) {
- String hql = ”select en from ” + entityClazz.getSimpleName() + “ en”;
- return find(hql);
- }
- @Override
- public long findCount(Class<T> entityClazz) {
- String hql = ”select count(*) from ” + entityClazz.getSimpleName();
- List<T> list = find(hql);
- if (list != null && list.size() == 1) {
- return (Long) list.get(0);
- }
- return 0;
- }
- /**
- * 根据HQL语句查询实体
- * @param hql 待查询的HQL语句
- * @return
- */
- @SuppressWarnings(“unchecked”)
- protected List<T> find(String hql) {
- return sessionFactory.getCurrentSession()
- .createQuery(hql)
- .list();
- }
- /**
- * 根据带占位符参数HQL语句查询实体
- * @param hql 待查询的HQL语句
- * @param params 参数
- * @return
- */
- @SuppressWarnings(“unchecked”)
- protected List<T> find(String hql, Object… params) {
- Query<T> query = sessionFactory.getCurrentSession().createQuery(hql);
- for (int i=0, len=params.length; i<len; i++) {
- query.setParameter(i + ”“, params[i]);
- }
- return query.list();
- }
- /**
- * 使用hql 语句进行分页查询操作
- * @param hql 需要查询的hql语句
- * @param pageNo 查询第pageNo页的记录
- * @param pageSize 每页需要显示的记录数
- * @return 当前页的所有记录
- */
- @SuppressWarnings(“unchecked”)
- protected List<T> findByPage(String hql, int pageNo, int pageSize) {
- Query<T> query = sessionFactory.getCurrentSession().createQuery(hql);
- return query.setFirstResult((pageNo-1) * pageSize)
- .setMaxResults(pageSize)
- .list();
- }
- /**
- * 使用hql 语句进行分页查询操作
- * @param hql 需要查询的hql语句
- * @param pageNo 查询第pageNo页的记录
- * @param pageSize 每页需要显示的记录数
- * @param params 如果hql带占位符参数,params用于传入占位符参数
- * @return 当前页的所有记录
- */
- @SuppressWarnings(“unchecked”)
- protected List<T> findByPage(String hql , int pageNo, int pageSize, Object… params) {
- Query<T> query = sessionFactory.getCurrentSession().createQuery(hql);
- for (int i=0, len=params.length; i<len; i++) {
- query.setParameter(i + ”“, params[i]);
- }
- return query.setFirstResult((pageNo - 1) + pageSize)
- .setMaxResults(pageSize)
- .list();
- }
- }
package com.wj.dao;
import java.io.Serializable;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseDao<T> implements IBaseDao<T> {
@Autowired
protected SessionFactory sessionFactory;
@Override
public T get(Class<T> entityClazz, Serializable id) {
return sessionFactory.getCurrentSession().get(entityClazz, id);
}
@Override
public Serializable save(T entity) {
return sessionFactory.getCurrentSession().save(entity);
}
@Override
public void update(T entity) {
sessionFactory.getCurrentSession().saveOrUpdate(entity);
}
@Override
public void delete(T entity) {
sessionFactory.getCurrentSession().delete(entity);
}
@Override
@SuppressWarnings("unchecked")
public boolean delete(Class<T> entityClazz, Serializable id) {
String hql = "delete " + entityClazz.getSimpleName() + " en where en.id = ?0";
Query<T> query = sessionFactory.getCurrentSession()
.createQuery(hql)
.setParameter("0", id);
return (query.executeUpdate() > 0);
}
@Override
public List<T> findAll(Class<T> entityClazz) {
String hql = "select en from " + entityClazz.getSimpleName() + " en";
return find(hql);
}
@Override
public long findCount(Class<T> entityClazz) {
String hql = "select count(*) from " + entityClazz.getSimpleName();
List<T> list = find(hql);
if (list != null && list.size() == 1) {
return (Long) list.get(0);
}
return 0;
}
/**
* 根据HQL语句查询实体
* @param hql 待查询的HQL语句
* @return
*/
@SuppressWarnings("unchecked")
protected List<T> find(String hql) {
return sessionFactory.getCurrentSession()
.createQuery(hql)
.list();
}
/**
* 根据带占位符参数HQL语句查询实体
* @param hql 待查询的HQL语句
* @param params 参数
* @return
*/
@SuppressWarnings("unchecked")
protected List<T> find(String hql, Object... params) {
Query<T> query = sessionFactory.getCurrentSession().createQuery(hql);
for (int i=0, len=params.length; i<len; i++) {
query.setParameter(i + "", params[i]);
}
return query.list();
}
/**
* 使用hql 语句进行分页查询操作
* @param hql 需要查询的hql语句
* @param pageNo 查询第pageNo页的记录
* @param pageSize 每页需要显示的记录数
* @return 当前页的所有记录
*/
@SuppressWarnings("unchecked")
protected List<T> findByPage(String hql, int pageNo, int pageSize) {
Query<T> query = sessionFactory.getCurrentSession().createQuery(hql);
return query.setFirstResult((pageNo-1) * pageSize)
.setMaxResults(pageSize)
.list();
}
/**
* 使用hql 语句进行分页查询操作
* @param hql 需要查询的hql语句
* @param pageNo 查询第pageNo页的记录
* @param pageSize 每页需要显示的记录数
* @param params 如果hql带占位符参数,params用于传入占位符参数
* @return 当前页的所有记录
*/
@SuppressWarnings("unchecked")
protected List<T> findByPage(String hql , int pageNo, int pageSize, Object... params) {
Query<T> query = sessionFactory.getCurrentSession().createQuery(hql);
for (int i=0, len=params.length; i<len; i++) {
query.setParameter(i + "", params[i]);
}
return query.setFirstResult((pageNo - 1) + pageSize)
.setMaxResults(pageSize)
.list();
}
}
4. 前台页面编写
本文重在展示框架的整合,前台测试代码此处就不贴了,有兴趣的可下载附件中的zip包。
完整项目下载链接:http://pan.baidu.com/s/1qY8vWTI 密码:grx7