Spring+Spring+Hibernate环境搭建

Posted dyh004

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring+Spring+Hibernate环境搭建相关的知识,希望对你有一定的参考价值。

 

一、引入lib包

pom.xml,引入需要的jar包

<?xml version="1.0" encoding="UTF-8"?>

<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>com.kszsa</groupId>
  <artifactId>ssht</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssht Maven Webapp</name>
  <!-- FIXME change it to the project‘s website -->
  <url>http://www.example.com</url>

  <properties>
    <!-- springmvc -->
    <spring.version>4.0.9.RELEASE</spring.version>
    <!-- hibernate -->
    <hibernate.version>4.1.0.Final</hibernate.version>
    <hibernate-validator.version>4.2.0.Final</hibernate-validator.version>
    <!--连接池-->
    <druid.version>1.1.9</druid.version>
    <!-- mysql -->
    <mysql.version>5.1.27</mysql.version>
    <!-- 测试依赖包 -->
    <junit.version>4.7</junit.version>

    <!-- 工具包 -->
    <!-- json start -->
    <jackson.version>1.8.4</jackson.version>
    <json-lib.version>2.1</json-lib.version>
    <fastjson-lib.version>1.2.31</fastjson-lib.version>
    <gson.version>2.2.4</gson.version>

    <!--maven插件变量-->
    <tomcat.version>2.2</tomcat.version>
    <jetty.version>7.6.14.v20131031</jetty.version>
    <webserver.port>8080</webserver.port>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>$spring.version</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>$spring.version</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>$spring.version</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>$spring.version</version>
    </dependency>
    <!-- spring orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>$spring.version</version>
    </dependency>
    <!-- spring mvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>$spring.version</version>
    </dependency>
    <!-- SPRING end -->
    <!-- web begin Spring MVC Test Framework 需要 servlet-api 3.0 以上  -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- aop aspect注解导包-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.12</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.12</version>
    </dependency>

    <!-- WEB end -->

    <!-- hibernate -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>$hibernate.version</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>$hibernate.version</version>
    </dependency>

    <!-- druid连接池  -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>$druid.version</version>
      <!-- <scope>runtime</scope> -->
    </dependency>

    <!--  mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>$mysql.version</version>
      <scope>runtime</scope>
    </dependency>
    <!-- TEST begin -->
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>$junit.version</version>
    </dependency>

    <!-- 工具包 -->
    <!-- JSON begin -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>$jackson.version</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>$json-lib.version</version>
      <classifier>jdk15</classifier>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>$fastjson-lib.version</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>$gson.version</version>
    </dependency>
    <!-- JSON end -->

  </dependencies>

  <build>
    <finalName>ssht</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
            <source>1.7</source>
            <target>1.7</target>
            <encoding>UTF-8</encoding>
          </configuration>
        </plugin>
        <!-- tomcat7插件 -->
        <plugin>
          <groupId>org.apache.tomcat.maven</groupId>
          <artifactId>tomcat7-maven-plugin</artifactId>
          <version>$tomcat.version</version>
          <configuration>
            <port>$webserver.port</port>
            <path>/$project.artifactId</path>
            <uriEncoding>$project.build.sourceEncoding</uriEncoding>
          </configuration>
        </plugin>

        <!-- 打包跳过单元测试 -->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.18.1</version>
          <configuration>
            <skipTests>true</skipTests>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

二、编写配置文件

编写Spring的配置文件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:aop="http://www.springframework.org/schema/aop"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:tx="http://www.springframework.org/schema/tx"
        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.3.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.3.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

    <!-- 扫描注解,注册bean -->
    <context:component-scan base-package="com.kszsa">
        <!-- 跳过@Controller -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

springMVC的配置文件 spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 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:aop="http://www.springframework.org/schema/aop"
       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.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://cxf.apache.org/jaxws
           http://cxf.apache.org/schemas/jaxws.xsd">

    <!-- mvc注解 -->
    <mvc:annotation-driven/>

    <!-- 扫描 -->
    <context:component-scan base-package="com.kszsa" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 视图解析 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 解析静态资源 -->
    <mvc:default-servlet-handler/>

</beans>

数据库连接信息配置文件config.properties

#database connection config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/xcjgk?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = root
diver_name=com.mysql.jdbc.Driver

validationQuery.sql=SELECT 1

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto =update

hibernate配置文件 spring-hibernate.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:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
       default-autowire="byName" default-lazy-init="false">

    <!-- hibernate -->
    <!-- 扫描properties配置文件 -->
    <context:property-placeholder location="classpath:config.properties"/>

    <!-- 配置数据源1 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="url" value="$jdbc.url" />
        <property name="username" value="$jdbc.username" />
        <property name="password" value="$jdbc.password" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="50" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="5" />

        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="$validationQuery.sql" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />

        <!-- 开启Druid的监控统计功能 -->
        <property name="filters" value="stat" />

        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="3600" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- Oracle连接是获取字段注释 -->
        <property name="connectProperties">
            <props>
                <prop key="remarksReporting">true</prop>
            </props>
        </property>

    </bean>

    <!-- session工厂 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="com.kszsa"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">$hibernate.hbm2ddl.auto</prop>
                <prop key="hibernate.dialect">$hibernate.dialect</prop>
                <prop key="hibernate.show_sql">$hibernate.show_sql</prop>
                <prop key="hibernate.format_sql">$hibernate.format_sql</prop>
            </props>
        </property>
    </bean>

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

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


</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">
    <display-name>ssht</display-name>

    <!-- 乱码的处理 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- spring start -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml,classpath*:spring-*.xml</param-value>
<!--        <param-value>classpath:applicationContext.xml</param-value>-->
    </context-param>

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

    <!-- spring mvc start -->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- spring mvc end -->


</web-app>

至此配置文件编写完成

三、编写bean

编写User.java

package com.kszsa.user;

import javax.persistence.*;

@Entity
@Table(name="user")
public class User 
    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @Column(name="name")
    private String name;

    @Column(name="description")
    private String description;

    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 getDescription() 
        return description;
    

    public void setDescription(String description) 
        this.description = description;
    

四、编写 DAO

编写通用接口ICommonDao.java

package com.kszsa.common.dao;

import java.io.Serializable;
import java.util.List;

public interface ICommonDao<T,PK extends Serializable> 

    T load(PK id);

    T get(PK id);

    List<T> findAll();

    void persist(T entity);

    void add(T entity);

    void update(T entity);

    void delete(PK id);

    void flush();


编写UserDao.java

package com.kszsa.user.dao;

import com.kszsa.common.dao.ICommonDao;
import com.kszsa.user.User;


public interface UserDao extends ICommonDao<User, Integer> 

编写UserDao实现类 UserDaoImp.java

package com.kszsa.user.dao;

import com.kszsa.user.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImp implements UserDao 

    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() 
        return this.sessionFactory.getCurrentSession();
    
    @Override
    public User load(Integer id) 
        return (User)this.getSession().load(User.class,id);
    

    @Override
    public User get(Integer id) 
        return (User) this.getSession().get(User.class, id);
    

    @Override
    public List<User> findAll() 
        return this.getSession().createQuery("from User").list();
    

    @Override
    public void persist(User entity) 
        this.getSession().persist(entity);
    

    @Override
    public void add(User entity) 
        this.getSession().save(entity);
    

    @Override
    public void update(User entity) 
        this.getSession().update(entity);
    

    @Override
    public void delete(Integer id) 
        User user = this.get(id);
        try
            this.getSession().delete(user);
        catch(Exception e)
            e.printStackTrace();
        
    

    @Override
    public void flush() 
        this.getSession().flush();
    

五、编写service层

编写UserService.java

package com.kszsa.user.service;

import com.kszsa.user.User;
import com.kszsa.user.dao.UserDaoImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class UserService 
    public void show()
        System.out.println("userService is called...");
    
    @Autowired
    private UserDaoImp userDaoImp;

    public User getById(Integer id) 
        return this.userDaoImp.get(id);
    

    public List<User> findAll() 
        return this.userDaoImp.findAll();
    

    public void add(User user) 
        this.userDaoImp.add(user);
    

    public void update(User user) 
        this.userDaoImp.update(user);
    
    public void delete(Integer id) 
        this.userDaoImp.delete(id);
    

六、编写controller层

编写UserController.java

package com.kszsa.user.controllor;

import com.alibaba.fastjson.JSONObject;
import com.kszsa.user.User;
import com.kszsa.user.service.UserService;
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;

@Controller
@RequestMapping("/user")
public class UserControllor 

    @Autowired
    private UserService userService;

    @RequestMapping("hello")
    @ResponseBody
    public String hello(String name)
        userService.show();
        return "hello12345,"+name;
    
    @RequestMapping("ceshi")
    public String ceshi()
        return "ceshi";
    

    @RequestMapping("add")
    @ResponseBody
    public String add(User user)
        String result = "successs";
        userService.add(user);
        return result;
    

    @RequestMapping("delete")
    @ResponseBody
    public JSONObject delete(Integer id)
        JSONObject jsonObject = new JSONObject();
        Boolean success = true;
        String message = "删除用户成功";
        try 
            userService.delete(id);
        catch (Exception e)
            success = true;
            message = "删除用户异常,异常信息"+e.getMessage();
        
        jsonObject.put("success",success);
        jsonObject.put("message",message);
        return jsonObject;
    

    @RequestMapping("update")
    @ResponseBody
    public JSONObject update(User user)
        JSONObject jsonObject = new JSONObject();
        Boolean success = true;
        String message = "更新用户成功";
        try 
            userService.update(user);
        catch (Exception e)
            success = true;
            message = "更新用户异常,异常信息"+e.getMessage();
        
        jsonObject.put("success",success);
        jsonObject.put("message",message);
        return jsonObject;
    
    @RequestMapping("get")
    @ResponseBody
    public User get(Integer id)
        return userService.getById(id);
    

七、编写前台页面

在webapp目录下,编写首页index.jsp

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

在webapp/WEB-INF/目录下,新建ceshi.jsp

<html>
<head>
    <title>Title</title>
</head>
<body>
AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
</body>
</html>

 

至此,所有代码编写完成。

八、运行及接口测试

访问首页:http://localhost:8080/ssht/index.jsp

技术图片

 

 访问测试页面:http://localhost:8080/ssht/user/ceshi

技术图片

 

 访问hello,name的rest接口http://localhost:8080/ssht/user/hello?name=xiaodu

技术图片

 

 访问用户添加页面:http://localhost:8080/ssht/user/add?name=libai&description=shiren

技术图片

 

 

去数据库中查询新增的记录 

技术图片

 

 

访问查询用户页面:http://localhost:8080/ssht/user/get?id=6

技术图片

 

 访问删除用户界面:http://localhost:8080/ssht/user/delete?id=6

技术图片

 

 到数据库中,查询,发现记录已经删除

技术图片

 

以上是关于Spring+Spring+Hibernate环境搭建的主要内容,如果未能解决你的问题,请参考以下文章

spring 学习之三(spring 与hibernate, struts2整合)

eclipse环境下基于已构建struts2项目整合spring+hibernate

Spring+Hibernate+SQL Server之Web开发环境设置浅谈

Spring+Springmvc+Hibernate环境搭建与配置

spring mvc4.1.6 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明

Spring:Spring整合Hibernate