Spring+SpringMVC+Hibernate整合(封装CRUD操作)

前言:当前Web项目开发的框架主流应该非Spring+SpringMVC+Hibernate莫属,不管是工作还是学习中涉及框架技术,首先是要搭建一套运行环境,虽然网上框架整合的教程很多,但我还是输出此文,一是自己总结整理可巩固理解,二是可供有需要学习的同仁参考。本着负责人的态度,本文所有内容测试通过,运行环境为JDK8+Tomcat8,Spring4.3.9,Hibernate5.2.10.

本篇文章重点关注以下问题:

  • 框架配置文件的编写
  • 后台Controller、Service、Dao层编写
  • 在Dao层封装基本CRUD操作
  • 前台页面编写

备注:本文为简明扼要,只在代码中对关键之处进行说明,有关框架的具体使用细节,可查阅相关资料,当然,自认为代码中的说明已够详细。另外,所有配置都是基于注解的方式实现。

 

项目结构:

 
Spring+SpringMVC+Hibernate整合(封装CRUD操作)_第1张图片
 

1. 配置文件

1.1 web.xml

      web.xml为web项目的入口,因此首先配置web.xml. 文件中配置的编码格式和session并不是必须的,但又是很常用的,所以就一并附上了。




    
    
        contextConfigLocation
        /WEB-INF/applicationContext.xml
    
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
        springMVC
        org.springframework.web.servlet.DispatcherServlet
        
              contextConfigLocation
              /WEB-INF/spring-mvc.xml
        
         1
    
    
        springMVC
        *.action
    
    
    
    
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    
    
        encodingFilter
        /*
    
    
    
    
        openSession
        org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
    
    
        openSession
        /*
    
    
    
        login.jsp
    

  1.2 SpringMVC配置文件



    
    
    

    
    
    
    
    
    

    
    
        
        
        
        
    

 1.3 Spring配置文件



    
    
    
    
    
    
    
    
    
    
        
        
        
        
    
    
    
    
        
        
            
                
                org.hibernate.dialect.MySQLDialect
                
                update
                true
                true
            
        
        
        
            
                com.wj.entity.User
            
        
    
    
    
    
        
    
    

 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 + "]";
    }
}

 

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 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 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 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 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 implements IUserDao {

    @Override
    public User getUser(String id) {
        return get(User.class, id);
    }

    @Override
    public List 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 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 {
    
    /**
     * 根据ID加载实体
     * @param entityClazz
     * @param id
     * @return
     */
    T get(Class 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 entityClazz , Serializable id);
    
    /**
     * 获取所有实体
     * @param entityClazz
     * @return
     */
    List findAll(Class entityClazz);
    
    /**
     * 获取实体总数
     * @param entityClazz
     * @return
     */
    long findCount(Class 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 implements IBaseDao {

    @Autowired
    protected SessionFactory sessionFactory;
    
    @Override
    public T get(Class 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 entityClazz, Serializable id) {
        String hql = "delete " + entityClazz.getSimpleName() + " en where en.id = ?0";
        Query query = sessionFactory.getCurrentSession()
                                 .createQuery(hql)
                                 .setParameter("0", id);
        return (query.executeUpdate() > 0);
    }

    @Override
    public List findAll(Class entityClazz) {
        String hql = "select en from " + entityClazz.getSimpleName() + " en";
        return find(hql);
    }

    @Override
    public long findCount(Class entityClazz) {
        String  hql  = "select count(*) from " + entityClazz.getSimpleName();
        List 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 find(String hql) {
        return sessionFactory.getCurrentSession()
                             .createQuery(hql)
                             .list();
    }
    
    /**
     * 根据带占位符参数HQL语句查询实体
     * @param hql           待查询的HQL语句
     * @param params        参数
     * @return
     */
    @SuppressWarnings("unchecked")
    protected List find(String hql, Object... params) {
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        
        for (int i=0, len=params.length; i findByPage(String hql, int pageNo, int pageSize) {
        Query 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 findByPage(String hql , int pageNo, int pageSize, Object... params) {
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        for (int i=0, len=params.length; i

 4. 前台页面编写

       本文重在展示框架的整合,前台测试代码此处就不贴了,有兴趣的可下载附件中的zip包。

 

完整项目下载链接:http://pan.baidu.com/s/1qY8vWTI 密码:grx7

你可能感兴趣的:(框架整合)