首页 > 代码库 > SpringMVC4+Hibernate5+SQLServer 2014 整合(包括增删改查分页)

SpringMVC4+Hibernate5+SQLServer 2014 整合(包括增删改查分页)

前言

     前面整合完了SpringMVC+MyBatis,自然也少不了SpringMVC+Hibernate,严格来说Hibernate才是我们真正想要的ORM框架么。只记得最初学习hibernate时,又是config.xml又是hml.xml,各种的xml。 今天试着用SpringMVC4整合Hibernate5,使用自动扫描注解的方式处理hibernate类文件,几乎零配置,这就爽很多了是不是。

 

开发环境

    SpringMVC4、Hibernate5、SQLServer2014

 

项目结构

技术分享

SpringMVC+Hibernate整合

1、查询分页数据

技术分享

   从控制台里看hql执行情况

技术分享

2、pom.xml,先把依赖的jar准备好

技术分享
 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3   <modelVersion>4.0.0</modelVersion> 4   <groupId>com.autohome</groupId> 5   <artifactId>SpringMVC6</artifactId> 6   <packaging>war</packaging> 7   <version>1.0-SNAPSHOT</version> 8   <name>SpringMVC6</name> 9   <url>http://maven.apache.org</url>10   <dependencies>11     <dependency>12       <groupId>org.springframework</groupId>13       <artifactId>spring-beans</artifactId>14       <version>4.3.6.RELEASE</version>15     </dependency>16     <dependency>17       <groupId>org.springframework</groupId>18       <artifactId>spring-context</artifactId>19       <version>4.3.6.RELEASE</version>20     </dependency>21     <dependency>22       <groupId>org.springframework</groupId>23       <artifactId>spring-core</artifactId>24       <version>4.3.6.RELEASE</version>25     </dependency>26     <dependency>27       <groupId>org.springframework</groupId>28       <artifactId>spring-test</artifactId>29       <version>4.3.6.RELEASE</version>30     </dependency>31     <dependency>32       <groupId>org.springframework</groupId>33       <artifactId>spring-web</artifactId>34       <version>4.3.6.RELEASE</version>35     </dependency>36     <dependency>37       <groupId>org.springframework</groupId>38       <artifactId>spring-webmvc</artifactId>39       <version>4.3.6.RELEASE</version>40     </dependency>41     <dependency>42       <groupId>org.springframework</groupId>43       <artifactId>spring-jdbc</artifactId>44       <version>4.3.6.RELEASE</version>45     </dependency>46     <dependency>47       <groupId>org.springframework</groupId>48       <artifactId>spring-orm</artifactId>49       <version>4.3.6.RELEASE</version>50     </dependency>51     <dependency>52       <groupId>junit</groupId>53       <artifactId>junit</artifactId>54       <version>4.10</version>55     </dependency>56     <!--servlet-->57     <dependency>58       <groupId>javax.servlet</groupId>59       <artifactId>javax.servlet-api</artifactId>60       <version>3.1.0</version>61     </dependency>62     <!--hibernate-->63     <dependency>64       <groupId>org.hibernate</groupId>65       <artifactId>hibernate-core</artifactId>66       <version>5.2.9.Final</version>67     </dependency>68     <dependency>69       <groupId>com.microsoft.sqlserver</groupId>70       <artifactId>sqljdbc4</artifactId>71       <version>4.0</version>72     </dependency>73     <!-- 支持jstl在jsp的应用 -->74     <dependency>75       <groupId>jstl</groupId>76       <artifactId>jstl</artifactId>77       <version>1.2</version>78     </dependency>79 80     <dependency>81       <groupId>taglibs</groupId>82       <artifactId>standard</artifactId>83       <version>1.1.2</version>84     </dependency>85 86   </dependencies>87   <build>88     <finalName>SpringMVC6</finalName>89   </build>90 </project>
View Code

3、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">  <display-name>Archetype Created Web Application</display-name>  <!--告知javaEE容器,有那些内容需要添加到上下文里去-->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value>  </context-param>  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!--spring 前端控制器-->  <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-servlet.xml</param-value>    </init-param>  </servlet>  <servlet-mapping>    <servlet-name>SpringMVC</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping></web-app>

4、springmvc-servlet.xml。这里整合主要配置jdbc数据源、hibernate sessionfactory、事务管理器

<?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:mvc="http://www.springframework.org/schema/mvc"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans.xsd       http://www.springframework.org/schema/context       http://www.springframework.org/schema/context/spring-context.xsd       http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc.xsd">    <!--从配置文件加载数据库信息-->    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="locations" value="classpath:config/jdbc.properties"/>        <property name="fileEncoding" value="UTF-8"/>    </bean>    <!--配置数据源,这里使用Spring默认-->    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="${sqlserver.driver}"/>        <property name="url" value="${sqlserver.url}"/>        <property name="username" value="${sqlserver.username}"/>        <property name="password" value="${sqlserver.password}"/>    </bean>    <!--配置hibernate sessionFacotry-->    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource"/>        <property name="hibernateProperties">            <props>                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>                <prop key="hibernate.show_sql">true</prop>                <prop key="hibernate.format_sql">true</prop>            </props>        </property>        <!--自动扫描注解的方式配置hibernate 类文件-->        <property name="packagesToScan">            <list>                <value>com.autohome.model</value>            </list>        </property>    </bean>    <!--配置事务管理器-->    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"/>    </bean>    <!--启用最新的注解器、映射器-->    <mvc:annotation-driven/>    <!--使用默认的Servlet来响应静态资源-->    <mvc:default-servlet-handler/>    <!--扫描Controller注解类-->    <context:component-scan base-package="com.autohome.controller"/>    <!--扫描Service注解类-->    <context:component-scan base-package="com.autohome.service"/>    <!--扫描Dao注解类-->    <context:component-scan base-package="com.autohome.dao"/>    <!--jsp视图解析器-->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/views/"/>        <property name="suffix" value=".jsp"/>    </bean></beans>

5、UserInfoDao

package com.autohome.dao;import com.autohome.model.UserInfo;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.query.Query;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import org.hibernate.Transaction;import java.util.List;@Repositorypublic class UserInfoDao {    @Autowired    private SessionFactory sessionFactory;    public List<UserInfo> listAllUser(){        String hql="from UserInfo";        Session session = sessionFactory.openSession();        Query query = session.createQuery(hql);        List<UserInfo> list = query.list();        return list;    }    public List<UserInfo> getAllUser(){        Session session = sessionFactory.openSession();        String sql="select * from t_userinfo";        //执行原生sql查询语句        Query query = session.createSQLQuery(sql);        List<UserInfo> list=query.list();        //执行原生增加、删除、修改语句        //query.executeUpdate();        return list;    }    public List<UserInfo> listPageUser(int offset,int rows){        String hql="from UserInfo";        Session session = sessionFactory.openSession();        Query query = session.createQuery(hql);        query.setFirstResult(offset);        query.setMaxResults(rows);        List<UserInfo> list = query.list();        return list;    }    public void save(UserInfo model){        Session session = sessionFactory.openSession();        Transaction tran=session.getTransaction();        tran.begin();        session.save(model);        tran.commit();    }    public void delete(Integer id){        String hql="delete from UserInfo where id=?";        Session session = sessionFactory.openSession();        Transaction tran=session.getTransaction();        tran.begin();        Query query = session.createQuery(hql);        query.setParameter(0,id);        query.executeUpdate();        tran.commit();    }    public void update(UserInfo model){        Session session = sessionFactory.openSession();        Transaction tran=session.getTransaction();        tran.begin();        session.update(model);        tran.commit();    }}

6、UserInfoService

package com.autohome.service;import com.autohome.dao.UserInfoDao;import com.autohome.model.UserInfo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class UserInfoBiz {    @Autowired    UserInfoDao userInfoDao;    public List<UserInfo> listAllUser(){        return userInfoDao.listAllUser();    }    public List<UserInfo> getAllUser(){        return userInfoDao.getAllUser();    }    public List<UserInfo> listPageUser(int offset,int rows){        return userInfoDao.listPageUser(offset,rows);    }    public void save(UserInfo model){        userInfoDao.save(model);    }    public void update(UserInfo model){        userInfoDao.update(model);    }    public void delete(Integer id){        userInfoDao.delete(id);    }}

 7、UserController

package com.autohome.controller;import com.autohome.model.UserInfo;import com.autohome.service.UserInfoBiz;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import java.util.List;@Controller@RequestMapping("/User")public class UserController {    @Autowired    UserInfoBiz userInfoBiz;    @RequestMapping("/index")    public ModelAndView index(int pageIndex,int pageSize){//        UserInfo model=new UserInfo();//        model.setName("zhangsan");//        model.setAddress("USA2017-03-28");////        userInfoBiz.save(model);//        UserInfo model=new UserInfo();//        model.setId(1);//        model.setName("李四");//        model.setAddress("USA2017-03-28");//        userInfoBiz.update(model);        // userInfoBiz.delete(51);        List<UserInfo> list = userInfoBiz.listPageUser((pageIndex-1)*pageSize,pageSize);        List<UserInfo> users = userInfoBiz.getAllUser();        System.out.println("size:"+users.size());        ModelAndView mav =new ModelAndView("index");        mav.addObject("list",list);        mav.addObject("title","用户列表");        return mav;    }}

 

8、UserInfo POJO

package com.autohome.model;import javax.persistence.*;import java.io.Serializable;@Entity@Table(name="t_userinfo")public class UserInfo implements Serializable {    @Id    @Column(name="id")    @GeneratedValue(strategy =GenerationType.IDENTITY)    private Integer id;    @Column(name="name")    private String name;    @Column(name="address")    private String address;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }}

  

总结

     在做这个整合demo的时候遇到两个问题,第一是实现分页调用querysetFirstResult和setMaxResults一直报一个索引超出。后更改hibernate断言SQLServer2008Dialect,一开始我用的是SQLServerDialect,因为本地连接sql server2014。第二是在jsp中用jstl显示controller中传过来的值时jsp中无法显示,百度了下是mavel默认生成web.xml的命名空间导致的(查看上面贴的web.xml代码)

     另外记得以前学习hibernate类文件全部是用hml.xml来写,现在则是直接扫描model包内的所有实体,实体使用Entity、Table、ID、Column注解,sql server id自增用注解GeneratedValue(strategy =GenerationType.IDENTITY),也确实从项目开发效果和代码整洁程度有很大提高。

 

参考

http://blog.csdn.net/xumengxing/article/details/8728255

https://my.oschina.net/zimingforever/blog/216909

 

SpringMVC4+Hibernate5+SQLServer 2014 整合(包括增删改查分页)