关闭

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

标签: hibernatespringmaven
84人阅读 评论(0) 收藏 举报
分类:

声明:本文是关于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>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3209次
    • 积分:141
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:4篇
    • 译文:1篇
    • 评论:0条