springMVC+hibernate构建项目

这几天要用到springMVC+spring+hibernate构建框架,使用的是eclipse今天闲下来把这些记录下来

首先要导入spring 的jar包和hibernate的jar包

这是所有的jar

然后让我们开始配置我们按照spring提倡“约定优于配置”将spring为servlet 的名称spring-servlet.xml将这个文件放在/WEB-INF下spring会自动去加载

spring-servlet.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
  <!--在这里配置controller所在的包的位置-->
    <context:component-scan base-package="com.test.controller"></context:component-scan>

<!--使用注解扫描-->
    <mvc:annotation-driven/>
    


    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property> //页面所在的文件夹
        <property name="suffix" value=".jsp"></property>//拦截后跳转的页面的后缀名的还原
    </bean>
    

<!--        文件上传配置信息-->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1000000"></property>//设置文件的上传大小
    </bean>
    
</beans>

 

以上为spring-servlet.xml的配置信息

下面介绍application.xml里的配置信息

application.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    

  //启用注解扫描
        <context:component-scan base-package="com.test"></context:component-scan>

  //  使用注解的方式管理事务
        <tx:annotation-driven transaction-manager="transactionManager"/>
        
      //数据源 
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
            <property name="user" value="root"></property>
            <property name="password" value="admin"></property>
        </bean>
        

       //事务管理
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>        
        </bean>
        

      //sessionFactory工厂
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                </props>
            </property>
            
       
    配置实体所在的包路径       
            <property name="mappingDirectoryLocations">
                <list>
                    <value>classpath:com/test/entity</value>
                </list>
            </property>
        </bean>
        

</beans>

 

下面开始配置web.xml文件中的文件信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
<!--     spring监听 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
<!--     处理中文乱码问题 -->
    <filter>
        <filter-name>EcodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>EcodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
<!--     过滤所有后缀名为html结尾的请求 -->
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    
</web-app>
以上是所有的配置文件的信息,下面对每个层次上的代码给予简单的介绍

UserInfoController.java:

package com.test.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.test.entity.UserInfo;
import com.test.service.UserInfoService;

@Controller
@RequestMapping("/user")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    private UserInfo userInfo;
    
    /**
     * 添加用户信息
     * @return
     */
    @RequestMapping("/add")
    public String add(UserInfo userinfo){
            this.userInfoService.save(userinfo);
        //重定向到list页面显示已添加的用户信息
        return "redirect:list.html";
    }

//查询出所有的用户信息

    @RequestMapping("/list")
    public String list(HttpSession session){
        List<UserInfo> userList = this.userInfoService.queryAll();
        session.setAttribute("userList", userList);
        return "user_list";
    }

 

    /**
     * 删除用户的信息
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable int id){
        this.userInfoService.delete(id);
        return "redirect:/user/list.html";
    }


    以上给出了简单的添加,删除,和查询,其他的操作也比较简单在这里不做详细介绍

UserInfoService.java:

package com.test.service.impl;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.test.dao.UserInfoDao;
import com.test.entity.UserInfo;
import com.test.service.UserInfoService;


@Service("userInfoService")
@Transactional
public class UserInfoServiceImpl implements UserInfoService{

    @Resource()
    private UserInfoDao userInfoDao;
    
    /**
     * 添加保存用户信息
     */
    @Override
    public void save(UserInfo userInfo) {
        userInfoDao.save(userInfo);
        
    }

    /**
     * 删除用户信息
     */
    @Override
    public void delete(Integer id) {
        UserInfo user = this.userInfoDao.queryById(id);
        this.userInfoDao.delete(user);
    }

 

    /**
     * 查询出所有的用户的信息
     */
    @Override
    public List<UserInfo> queryAll() {
        return this.userInfoDao.queryAll();
    }

 

这里的代码太简单,不多说

 

UserInfoDaoImpl.java

 

package com.test.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.test.dao.UserInfoDao;
import com.test.entity.UserInfo;

@Repository("userDao")
public class UserDaoImpl extends HibernateDaoSupport implements UserInfoDao {

    @Resource
    public void setSuperSessionFactory(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }
    
/**
 * 添加用户信息
 */
    @Override
    public void save(UserInfo userInfo) {
        super.getHibernateTemplate().save(userInfo);
    }

    /**
     * 删除用户信息
     */
    @Override
    public void delete(UserInfo userInfo) {
        super.getHibernateTemplate().delete(userInfo);
    }

/**
 * 查询出所有的用户信息
 */
    @Override
    public List<UserInfo> queryAll() {
        String hql = "from UserInfo";
        return super.getHibernateTemplate().find(hql);
    }

 

这是一种比较费时,费力的写法,当然也有比较简单的,比较的通用

BaseDaoImpl.java

package com.test.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;



public class BaseDaoImpl<T> extends HibernateDaoSupport {

    private Class<T> entityClass;
    
    @Resource(name = "sessionFactory")  
    public void setSuperSessionFactory(SessionFactory sessionFactory) {  
            super.setSessionFactory(sessionFactory);  
        }  
    
    /**
     *获取类
     */
    public BaseDaoImpl(){
//        Type genType = this.getClass().getGenericSuperclass();
//        Type[] params = ((ParameterizedType)getClass()).getActualTypeArguments();
//        entityClass = (Class<T>) params[0];
        this.entityClass = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        System.out.println("entityClass ============= "+this.entityClass);
    }
    
    public BaseDaoImpl(Class clazz){
        this.entityClass = clazz;
    }
    
    /**
     *    根据编号获取实体信息
     * @param id  传入的用户的编号
     * @return 返回实体
     */
    public T get(Serializable id){
        return super.getHibernateTemplate().get(entityClass, id);
    }
    
    /**
     * 保存实体对象
     * @param entity 传入的实体对象
     */
    public void save(T entity){
        super.getHibernateTemplate().save(entity);
    }
    
    /**
     * 删除的实体信息
     * @param entity 传入的实体信息
     */
    public void deleteEntity(T entity){
        super.getHibernateTemplate().delete(entity);
    }
    
    /**
     * 更新的实体信息
     * @param entity 更新后的实体信息
     */
    public void updateEntity(T entity){
        super.getHibernateTemplate().update(entity);
    }
    
    /**
     * 根据传入的hql语句进行查询
     * @param hql    查询的hql语句
     * @return  返回查询的结果
     */
    public List<T> find(String hql){
        return super.getHibernateTemplate().find(hql);
    }
    
    
    /**
     *  带参数查询
     * @param hql  hql语句
     * @param params  传入查询的参数
     * @return  返回查询的结果
     */
    public List<T> find(String hql, Object...params){
        return super.getHibernateTemplate().find(hql, params);
    }
    
    /**
     * 创建Query方式查询
     * @param hql  hql语句
     * @param params 查询的参数
     * @return  返回Query对象
     */
    public Query createQuery(String hql, Object... params){
        Query query = this.getSession().createQuery(hql);
        if( params != null && params.length > 0){
            
        for(int i = 0; i < params.length; i++){
            query.setParameter(i, params[i]);
        }
        }
        return query;
    }
    
    /**
     * 统计一共有多少条数据 当让也可以添加上参数,这个后续完善
     * @return
     */
    public int getCount(){
        String hql = "select count(e) from  "+entityClass.getSimpleName()+" e ";
        Query query = this.createQuery(hql,null);
        Long count = (Long) query.uniqueResult();
        return count.intValue();
    }
    
    /**
     * 根据编号查询出
     * @param id  传入的实体的编号信息
     * @return   返回一个对应的实体对象
     */
    public T queryById(int id){
        return this.get(id);
    }
    
    /**
     * 分页显示数据信息,当然和getCount一样也可以添加上参数,后续完善
     *
     * @param page  分页的page实体
     * @return  返回查询的集合结果
     */
//    public List<T> queryAll(Page page) {
//        String hql = "from "+entityClass.getSimpleName();
//        Query query = this.createQuery(hql, null);
//        
//        //设置起始位置
//        query.setFirstResult((page.getCurrentPage()-1)*page.getEveryPage());
//        
//        //设置每页显示的数量
//        query.setMaxResults(page.getEveryPage());
//        List<T> list = query.list();
//        return list;
//    }
    
    
    /**
     * 查询所有的数据信息,相信很少会用到
     */
    public List<T> queryAll(){
        String hql = "from "+entityClass.getSimpleName();
        List<T> list = find(hql);
        return list;
    }
    
}

 

 

posted @ 2013-08-22 18:21  唐凯  阅读(391)  评论(0编辑  收藏  举报