Spring mvc4 + Hibernate5 Maven项目搭建

Spring mvc4 + Hibernate5 Maven项目搭建

1. pom.xml 文件配置


   <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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>bank</groupId>
  <artifactId>spring-mvc-web</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
    <!-- spring mvc 包含大部分的spring jar包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <!-- 包含spring事务管理,spring对hibernate的封装等 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <!-- hibernate核心包 SessionFactory 、 session等 -->
    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-core</artifactId>
       <version>5.2.10.Final</version>
    </dependency>

    <!-- mysql jdbc 不解释-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>

    <!--dbcp 数据库连接dbcp包 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.1.1</version>
    </dependency>    
    <!-- json解析 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.7</version>
    </dependency>

  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project> 

2. web.xml 配置


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <!-- spring 所需applicationContext.xml配置文件路径,如果不配置,默认在WEB-INFO目录下寻找 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/conf/applicationContext.xml </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring mvc 入口 -->
    <servlet>
        <servlet-name>bank</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- spring mvc配置文件路径配置,不过不配置,默认在WEB-INFO目录下寻找'servlet-name'-servlet.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/conf/bank-servlet.xml</param-value>
        </init-param>
    </servlet>

    <filter>
       <filter-name>OpenSessionInViewFilter</filter-name>
            <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
       <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
       </init-param>
    </filter>

    <filter-mapping>
       <filter-name>OpenSessionInViewFilter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet-mapping>
        <servlet-name>bank</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

3. applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <!-- mysql.jdbc 6 要求必须添加这个参数 -->
        <property name="url" value="jdbc:mysql://192.168.1.102:3306/bank?serverTimezone=UTC " />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <!--minIdle: 最小空闲连接 -->
        <property name="minIdle" value="5" />
        <!--maxIdle: 最大空闲连接 -->
        <property name="maxIdle" value="20" />
        <!--initialSize: 初始化连接 -->
        <property name="initialSize" value="30" />
    </bean>
    <!-- spring 包扫描 -->
    <context:component-scan base-package="com.bank.base"></context:component-scan>
    <!-- 配置SessionFactory -->
    <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.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext
                </prop>
                <!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
            </props>
        </property>
        <property name="packagesToScan" value="com.bank.base.entity" />
    </bean>
    <!-- spring提供的一个,封装好的hibernate帮助类 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 配置一个事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <!-- <property name="dataSource" ref="dataSource" /> 不需要再次注入数据源-->
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

4. xxx-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<!-- Bean头部 -->
<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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" 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-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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <!-- 激活@Controller模式 -->
    <mvc:annotation-driven />
    <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 需要更改 -->
    <context:component-scan base-package="com.bank.base.controller" />

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

至此,这个项目的配置文件就告一段落

5. Controller


package com.bank.base.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bank.base.entity.User;
import com.bank.base.service.BaseService;

@Controller
@RequestMapping(value = "bank")
public class BaseController {

    @Autowired
    private BaseService baseService;

    @RequestMapping(value = "success")
    @ResponseBody
    public String success() {
        System.out.println("im here");
        return "success";
    }

    @RequestMapping(value = "reg")
    @ResponseBody
    public String reg(User user) {
        baseService.register(user);
        return "ok";
    }

    @RequestMapping(value = "find")
    @ResponseBody
    public User findUser(int id){
        return baseService.findUserById(id);
    }

    @RequestMapping(value = "del")
    @ResponseBody
    public String delete(int id){
        baseService.delete(id);
        return "success";
    }
}

7. Service


package com.bank.base.service;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bank.base.dao.BaseDao;
import com.bank.base.entity.User;

@Service
public class BaseService {

    @Autowired
    private BaseDao baseDao;

    @Transactional
    public void register(User user){
        baseDao.add(user);
    }

    public User findUserById(int id){
        return baseDao.get(id);
    }

    @Transactional
    public void delete(int id){
        baseDao.delete(id);
    }
}

8. Dao


    package com.bank.base.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bank.base.entity.User;

@Repository
public class BaseDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Transactional
    public void add(User user) {
        this.hibernateTemplate.save(user);
    }

    public User get(int id) {
        return getSession().get(User.class, id);
    }

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Transactional
    public void delete(int id) {
        Session session = getSession();
        User user = get(id);
        session.delete(user);
    }
}

亲测成功!
后续会搭建项目中遇到的一些问题在做深入的了解。

你可能感兴趣的:(maven,spring4,spring-mvc,Hibernate5)