SSH系列(二):Spring + Hibernate + SpringMVC Maven整合

原创 2016年08月30日 21:01:12

声明:本文是关于Spring4.3.2 + Hibernate5.1.0 + SpringMVC Maven方式的简单整合。pom.xml只添加了最基本的依赖,实际开发中需要的依赖根据项目具体添加; 本文不详细说明maven安装与使用。不当的地方欢迎大家指正,不胜感激。

整合环境

JDK 1.7
Tomcat:apache-tomcat-7.0.59
Spring:spring-framework-4.3.2.RELEASE
Hibernate:hibernate-release-5.1.0.Final

Maven工程目录结构

Maven工程目录结构

整合步骤

MyEclipse中创建Maven工程

File –> New –> Project:

第一步

Next:

第二步

选择创建原型:

第三步

指定原型参数:groupId、ArtifactID 和 version 等

第四步

注意:此时创建好工程中目录如下图,需要自己添加src/main/java、src/test/resource、src/test/java等目录

Maven工程结构图

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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>
  <artifactId>spring_web_mvc_hibernate_maven_01</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>

  <name>spring_web_mvc_hibernate_maven_02</name>
  <url>http://maven.apache.org</url>

  <properties>
    <springframework.version>4.3.2.RELEASE</springframework.version>
    <hibernate.version>5.1.0.Final</hibernate.version>
    <mysql.connector.version>5.1.13</mysql.connector.version>
    <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
    <javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version>
    <jstl.version>1.2</jstl.version>
    <commons-dbcp.version>1.4</commons-dbcp.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

<!-- Spring -->
    <!-- 
        引入这个依赖会同时引入:
            spring-core-${springframework.version}.jar
            commons-logging-1.2.jar
     -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <!-- 
        引入这个依赖会同时引入:
            spring-web-${springframework.version}.jar
            spring-aop-${springframework.version}.jar
            spring-beans-${springframework.version}.jar
            spring-context-${springframework.version}.jar
            spring-expression-${springframework.version}.jar
     -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <!-- 
        引入这个依赖会同时引入:
            spring-webmvc-${springframework.version}.jar 
     -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <!-- 
        引入这个依赖会同时引入:
            spring-tx-${springframework.version}.jar
     -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <!-- 
        引入这个依赖会同时引入:
            spring-orm-${springframework.version}.jar
            spring-jdbc-${springframework.version}.jar
     -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <!-- Hibernate -->
    <!-- 
        引入这个依赖会同时引入:
            hibernate-core-5.1.0.Final.jar
            jboss-logging-3.3.0.final.jar
            hibernate-jpa-2.1-apo-1.0.0.Final.jar
            javassist-3.20.0-GA.jar
            antlr-2.7.7.jar
            geronimo-jta_1.1_spec-1.1.1jar
            jandex-2.0.0.Final.jar
            classmate-1.3.0.jar
            dom4j-1.6.1.jar
            xml-apis-1.0.b2.jar
            hibernate-commons-annotations-5.0.1.Final.jar
     -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

<!-- 数据库连接池配置 -->
    <!-- 
        引入这个依赖会引入的包:
            commons-dbcp-1.4.jar
            commons-pool-1.5.4.jar
     -->
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>${commons-dbcp.version}</version>
    </dependency>

<!-- 日志 -->
    <!-- 
        引入这个依赖会引入的包:
            log4j-1.2.17.jar
            slf4j-api-1.7.21.jar
            slf4j-log4j12-1.7.7.jar
     -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>

<!-- MySQL -->
    <!-- 
        引入这个依赖会同时引入:
            mysql-connector-java-5.1.13.jar
     -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.connector.version}</version>
    </dependency>

<!-- Servlet -->
    <!-- 
        引入这个依赖会同时引入:
            javax.servlet-api-3.1.0.jar
     -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet-api.version}</version>
    </dependency>

<!-- jsp -->
    <!-- 
        引入这个依赖会同时引入:
            javax.servlet.jsp-api-2.3.1.jar
     -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>${javax.servlet.jsp-api.version}</version>
    </dependency>

<!-- jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>spring_web_mvc_hibernate_maven_02</finalName>
  </build>
</project>

代码示例

User:

package com.test.model;

import java.io.Serializable;

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 implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1405461442424049597L;
    private Integer uid;
    private String username;
    private String password;

    public User(Integer uid, String username, String password) {
        super();
        this.uid = uid;
        this.username = username;
        this.password = password;
    }

    public User(String username, String password) {
        this(null, username, password);
    }

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    @Column(name = "uname")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "password")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Dao层:

IUserDao:

package com.test.dao;

import java.util.List;

import com.test.model.User;

public interface IUserDao {
    public List<User> findAllUser();
}

UserDaoImpl:

package com.test.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.test.dao.IUserDao;
import com.test.model.User;

@Repository
public class UserDaoImpl implements IUserDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<User> findAllUser() {
        String hql = "from User";
        Session session = sessionFactory.openSession();

        return session.createQuery(hql).list();
    }
}

Service层:

IUserService:

package com.test.service;

import java.util.List;

import com.test.model.User;

public interface IUserService {
    public List<User> findAllUser();
}

UserServiceImpl:

package com.test.service.impl;

import java.util.List;

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

import com.test.dao.IUserDao;
import com.test.model.User;
import com.test.service.IUserService;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;

    @Override
    @Transactional(readOnly = true)
    public List<User> findAllUser() {
        return userDao.findAllUser();
    }
}

Controller层:

package com.test.controller;

import java.util.List;

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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.test.model.User;
import com.test.service.IUserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView getAllUser() {
        List<User> list = userService.findAllUser();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList", list);
        modelAndView.setViewName("/welcome");

        return modelAndView;
    }
}

配置文件

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

applicationContext.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<!-- 扫描dao层的注解 -->
    <context:component-scan base-package="com.test.dao.impl"/>

    <!-- 加载数据库配置文件:db.properties -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 配置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.MySQLDialect</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.temp.use_jdbc_metadata_defaults">false</prop>
            </props>
        </property>
        <!-- 配置需要扫描包的路径,在该包下,所有的类注解配置都会被扫描 -->
        <property name="packagesToScan" value="com.test.model"/>
    </bean>

    <!-- 扫描Service层的注解 -->
    <context:component-scan base-package="com.test.service.impl"/>

    <!-- 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>  
    </bean>

    <!-- 开启注解事务开关 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

springmvc.xml

<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:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://code.alibabatech.com/schema/dubbo 
    http://code.alibabatech.com/schema/dubbo/dubbo.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 扫描带有Controller的注解类 -->
    <context:component-scan base-package="com.test.controller" />
    <!-- 加载注解驱动 -->
    <mvc:annotation-driven />
    <!-- 视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views"/>    
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

  <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>

  <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.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>
版权声明:本文为博主原创文章,未经博主允许不得转载。

Spring整合Struts2和Hibernate+Maven(二)之SSH的配置文件

上次讲到的是maven项目的创建以及pom.xml的配置。 这里推荐一个网站:maven整合jar包,这里可以查询并生成配置文件中jar包导入格式的文本,复制粘贴到pom.xml中即可由idea自动...

SSH系列(一):Spring + Hibernate + SpringMVC 整合

整合环境JDK 1.7 Tomcat:apache-tomcat-7.0.59 Spring:spring-framework-4.3.2.RELEASE Hibernate:hibernate-re...

用Maven整合SpringMVC+Spring+Hibernate 框架,实现简单的插入数据库数据功能(二)

前一篇写的有些多,大家先看前一篇,传送门 具体的资源已将上传到资源了。 附地址:MySQL.zip启动 用Maven整合SpringMVC+Spring+Hibernate 框架 上文我们...

Spring+SpringMVC+Mybatis整合系列(二)Eclipse新建Maven web项目

这是SSM搭建的第二篇,关于eclipse集成Maven的部分已经在上一篇中 Spring+SpringMVC+Mybatis整合系列(一)Maven安装和Eclipse配置详细介绍完,下面主要介绍使...

使用Maven实现Struts2+Hibernate4+Spring3整合SSH框架(二):导入Spring的jar包并添加测试实现

在maven项目中添加Spring4的支持,并测试搭建。

springmvc+mybatis+spring 整合 bootstrap html5 mysql oracle SSM框架源码 SSH maven

 获取【下载地址 (劳动所得,不喜勿喷)】 【免费支持更新】 A 代码生成器(开发利器);全部是源码      增删改查的处理类,service层,mybatis的xml,SQL( my...

Maven整合Spring+SpringMVC+Hibernate5

  • 2017年06月10日 15:56
  • 563KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:SSH系列(二):Spring + Hibernate + SpringMVC Maven整合
举报原因:
原因补充:

(最多只允许输入30个字)