首页 > 代码库 > springMVC+spring+hibernate 框架整合实例

springMVC+spring+hibernate 框架整合实例

先说一下流程思路:

流程讲解1:
首先访问会先定位到控制器。这就用到了过滤器配置文件“spring-mvc.xml”。这个文件负责定义控制器的包路径、视图的格式等。
其次从“控制器->service层->dao层”,期间用的都是spring的依赖注入,所以就需要一个bean容器配置文件,将所有的“等待被注入的类”在xml文件里申明一下。这个xml文件就是“spring-beans.xml”。
之后,dao层要操作entity里面的持久化类。dao必须通过sessionFactory里面的session才能操作持久化类。于是需要一个xml文件配置sessionFactory类,这个sessionFactory作为一个bean,可被注入到dao层。这个文件还需要将“entity里面所有的持久化类”申明出来。这个文件就是“spring-hibernate.xml”。
最后将这些xml配置文件全部在web.xml里面加载。

流程讲解2:
通过url地址,定位到控制器的具体方法。
之后控制器调用service层的实例做点什么(service层的实例是注入进来的)并且返回一个jsp页面。
service层的实例再调用dao层的实例做点什么(dao层的实例是注入进来的)。
dao层是底层数据层,dao层的实例通过sessionFactory来创建一个session操作具体的持久化类对象(sessionFactory对象是被注入进来的)对数据库进行“增删查改”等操作。

 

流程讲解3:
这个实例具体干的事是:UserDaoImpl从数据库里查询出用户信息列表,并将用户信息列表返回给UserServiceImpl。
UserServiceImpl经过处理得到某一个用户的用户名,并将用户名返回给控制器。
控制器再将这个用户名打印出来,然后调用一下视图jsp文件。

 

结构如下:

技术分享
 
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>java-ssh-demo3</name>
  <groupId>java-ssh-demo</groupId>
  <artifactId>java-ssh-demo3</artifactId>
  <version>1.0-SNAPSHOT</version>

  <!--项目依赖 -->
  <dependencies>
    <!--日志包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>

    <!--j2ee相关包 servlet、jsp、jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!--spring相关包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>




    <!--其他需要的包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- hibernate内置日志记录所需包-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
    </dependency>

    <!--mariadb驱动-->
    <dependency>
      <groupId>org.mariadb.jdbc</groupId>
      <artifactId>mariadb-java-client</artifactId>
      <version>1.5.5</version>
    </dependency>

    <!-- 代码生成类库 -->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
      <version>2.2.2</version>
    </dependency>

    <!--hibernate包-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.6.Final</version>
    </dependency>
    <!--hibernate校验器-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.2.4.Final</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>maven-springmvc</finalName>
    <resources>
      <!--表示把java目录下的有关xml文件,properties文件编译/打包的时候放在resource目录下-->
      <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
      </resource>
    </resources>

    <plugins>
      <!--servlet容器 jetty插件-->
      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.3.10.v20160621</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

 

 
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
         version="3.1">
  <display-name>java-springmvc-demo5</display-name>

    <!-- 配置Spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/spring-*.xml</param-value>
    </context-param>
    <!--listener用于在Web 应用启动时,启动某些后台程序,此处启动的是spring-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--定义入口类DispatcherServlet-->
    <servlet>
      <servlet-name>springMVC</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- 默认的servlet.xml文件是放在WEB-INF目录下,名称与<servlet-name>的名字要相关。但可以通过以下设置重新自定义servlet.xml配置文件的位置和名称。-->
      <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath*:config/spring-mvc.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>

    <!--欢迎页面-->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

    <!-- 设置OpenSessionInViewFilter 的过滤器,由 Spring 来控制 Hibernate 的 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>
</web-app>

 

spring-mvc.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:p="http://www.springframework.org/schema/p"
       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-3.0.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-3.0.xsd">

    <!-- 启动时自动扫描该包下所有的Bean -->
    <context:component-scan base-package="pers.cly.ssh_demo3.controller" />
    <!-- 添加注解驱动 -->
    <mvc:annotation-driven />
    <!--所有的访问都统一先由InternalResourceViewResolver类处理-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--定义跳转的文件的前缀(jsp文件所在目录)-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 定义跳转的文件的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

 

spring-beans.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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p" 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/util
       http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--启动时自动扫描该包下所有的Bean-->
    <context:component-scan base-package="pers.cly.ssh_demo3" />

    <!--注册一个UserDaoImpl对象,实例名为“userDao”-->
    <bean id="userDao" class="pers.cly.ssh_demo3.dao.impl.UserDaoImpl"/>

    <!--注册一个UserServiceImpl对象,实例名为“userService”-->
    <bean id="userService" class="pers.cly.ssh_demo3.service.impl.UserServiceImpl"/>
</beans>

 

spring-hibernate.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-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/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd   ">

<!-- 声明事务管理器 -->
<bean id="myHibTxManager"
      class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 定义事务通知 -->
<tx:advice id="tx_Advice" transaction-manager="myHibTxManager">
    <!-- 定义事务传播规则 -->
    <tx:attributes>
        <!-- 对get/load/search开头的方法应用只读事务规则 -->
        <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        <tx:method name="load*" propagation="SUPPORTS" read-only="true" />
        <tx:method name="search*" propagation="SUPPORTS" read-only="true" />
        <!-- 对其他方法应用REQUIRED事务规则 -->
        <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>

<!--<aop:config>-->
    <!--&lt;!&ndash; 对com.zxpm.biz包下的所有类的所有方法都应用事务规则 &ndash;&gt;-->
    <!--<aop:pointcut id="bizMethods"-->
                  <!--expression="execution(* cn.zifangsky.service.*.*(..))" />-->
    <!--&lt;!&ndash; 将事务通知和切面组合 &ndash;&gt;-->
    <!--<aop:advisor advice-ref="tx_Advice" pointcut-ref="bizMethods" />-->
<!--</aop:config>-->

<!-- 配置数据源 -->
<bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.mariadb.jdbc.Driver"></property>
    <property name="url" value="jdbc:mariadb://localhost:3306/daixu"></property>
    <property name="username" value="root"></property>
    <property name="password" value="123"></property>
</bean>

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <!-- 申明entity中所有持久化类 -->
            <value>pers.cly.ssh_demo3.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>
</beans>

 

HelloController.java:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import pers.cly.ssh_demo3.service.UserService;

import javax.annotation.Resource;

@Controller//该注解用来识别控制器
@RequestMapping("hello")//该注解用来控制url书写时,控制器的选择
public class HelloController {
    @Resource(name="userService")  // 获取spring配置文件中bean的id为userService的具体实现类,并注入
    private UserService userServiceImpl;//service层的用户接口类。

    @RequestMapping("helloworld")//该注解用来控制url书写时,具体方法的选择(还可以绑定参数等)
    public String helloworld() {
        System.out.print("用户姓名:"+userServiceImpl.select_user_name());//调用接口方法获取用户姓名,打印用户姓名
        return "hello_world";//跳转到jsp页面
    }

}

 

UserService.java:

import pers.cly.ssh_demo3.entity.UserEntity;

/**
 * Created by CLY on 2016/12/26.
 */
public interface UserService {
    public String select_user_name();//这个方法负责查询用户姓名
}

 

UserServiceImpl.java:

import pers.cly.ssh_demo3.dao.UserDao;
import pers.cly.ssh_demo3.entity.UserEntity;
import pers.cly.ssh_demo3.service.UserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by CLY on 2016/12/26.
 */
public class UserServiceImpl implements UserService {
    @Resource(name = "userDao")//使用注解配置,将id为“userDao”的bean注入到“userDaoImpl”里面
    private UserDao userDaoImpl;//定义dao层的“接口”

    @Override
    public String select_user_name() {
        String user_name="";

        List<UserEntity> users = userDaoImpl.select_user();//通过接口方法,获取用信息列表


        for (UserEntity u : users) {//迭代列表,将里面的最后一个用户的姓名提取出来
            user_name = u.getUserName();
        }

        return user_name;//返回用户名
    }
}

 

UserDao.java:

import pers.cly.ssh_demo3.entity.UserEntity;

import java.util.List;

/**
 * Created by CLY on 2016/12/26.
 */
public interface UserDao {
    public List<UserEntity> select_user();//将用户信息查出,并返回用用户持久化类列表
}

 

UserDaoImpl.java:

import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import pers.cly.ssh_demo3.dao.UserDao;
import pers.cly.ssh_demo3.entity.UserEntity;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by CLY on 2016/12/26.
 */
public class UserDaoImpl implements UserDao {
    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;//注入sessionFactory

    @Override
    public List<UserEntity> select_user() {
        String hql = "from UserEntity";//hql语句
        Query query = sessionFactory.getCurrentSession().createQuery(hql);

        return query.list();
    }
}

 

UserEntity.java是我用idea根据表自动生成,就不贴代码了。

hello_world.jsp和index.jsp写什么随意,也不贴代码了。

 

之后用“http://localhost:8080/hello/helloworld”路径可访问出结果。

springMVC+spring+hibernate 框架整合实例