一步步搭建Springmvc+hibernate(2)——spring整合hibernate详解

上一篇,已经介绍如何搭建spring mvc框架。现在融入hibernate.

spring融合hibernate,现在很多人都是不懂,然后胡乱糅合一大推包,然后项目能运行就行了,别的都不考虑。但,这对于对于每一个包的作用,知识点理解都是不方便的。所以学习,还以一步步来。下面,我来介绍如何搭建ssh框架,每个jra包作用。

 <properties>
<springframework.version>4.0.6.RELEASE</springframework.version>
<hibernate.version>4.3.5.Final</hibernate.version>
    <mysql.version>5.1.34</mysql.version>
  </properties>
  
  <dependencies>

<!--junit测试,这里不多解释  很必要>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>


     <!--springmvc包  -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${springframework.version}</version>
    </dependency>


    <!--spring上下文-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${springframework.version}</version>
    </dependency>


    <!--spring 事务处理-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${springframework.version}</version>
    </dependency>


    <!--spring jdbc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${springframework.version}</version>
    </dependency>


    <!--spring aop 切面-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${springframework.version}</version>
    </dependency>


    <!--整合sessionfactory session工厂-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${springframework.version}</version>
    </dependency>  


    <!-- 处理事务和AOP所需的包 -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.4</version>
    </dependency>
    <!-- 处理事务和AOP所需的包  spring的切入点表达式需要用的包,  -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.4</version>
    </dependency>

<!--hibernatejar文件-->
<!--语言转换工具,hibernate利用它实现HQL到SQL的转换  -->
<dependency>
      <groupId>antlr</groupId>
      <artifactId>antlr</artifactId>
      <version>2.7.7</version>
    </dependency>
    <!--hibernate核心包-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>


    <!-- Hibernate EntityManager实现了EJB3.0 JPA规范。
         Hibernate Java Persistence provider通过了Sun TCK测试和完全认证,
                       你可以在Java SE 5.0,或Java EE 5.0以上的任何环境里使用
         Hibernate Java Persistence provider -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate.version}</version>
    </dependency>


    <!-- mysql连接 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>


    <!-- commons-dbcp数据源,用于配置数据库链接信息 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
    </dependency>


<!--servlet包,用户处理HttpServletRequest等请求,参数等问题  -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- jstl包,el表达式使用 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

  </dependencies>

需要的jar包目前就这些,其他的如果需要,自己可根据自己需要再添加。每个jar包作用,我这里都做了简要的介绍,所以不要在乱添加jar包文件了。

第二步:先创建配置文件,数据库配置文件jdbc.properties

# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useOldAliasMetadataBehavior=true
jdbc.username=root
jdbc.password=root


# hibernate.X
hibernate.connection.driverClass=org.gjt.mm.mysql.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/test
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.connection.username=root
hibernate.connection.password=root
hibernate.show_sql=true
#hibernate.hbm2ddl.auto=create-drop  //这里注意  如果选择create  项目启动每次会重新见表,原表数据会被删除
hibernate.hbm2ddl.auto=update

先创建hibernate实体类,可以使用逆向生成工具生成。

我这里手动创建的,只要注意相关配置参数即可


创建实体类:

package com.mx.model;


import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "user")   //name对应表明
public class User {

@Id     //主键
@GeneratedValue  
private int id;

@Basic
@Column(name = "username")
private String username;
@Basic
@Column(name = "password")
private String password;
@Basic
@Column(name = "type")
private String type;



    @Id
    @Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

@Basic
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}

@Basic
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Basic
@Column(name = "type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}


}


创建实体操作类:

package com.mx.dao;


import java.util.List;


import javax.annotation.Resource;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;


import com.mx.dao.IndexDao;
import com.mx.model.User;


@Service("indexDao")
public class IndexDaoImpl implements IndexDao {

@Resource(name="sessionFactory")
private SessionFactory sessionFactory;


public List<User> getList() {
// TODO Auto-generated method stub
String hql= "from User";      //看清了,这里不是表名,而是表对应的实体类的名称
    Session session=sessionFactory.getCurrentSession();
    Query query=session.createQuery(hql);
    return query.list();
}




}

创建操作接口



import java.util.List;


import com.mx.model.User;


public interface IndexDao {


public List<User> getList();


}

创建service层实现方法,当然,你也可以不用这样配置,我是习惯了。

package com.mx.service.impl;


import java.util.List;


import javax.annotation.Resource;


import org.springframework.stereotype.Service;


import com.mx.dao.IndexDao;
import com.mx.model.User;
import com.mx.service.IndexService;


@Service("indexService")
public class IndexServiceImpl implements IndexService{

@Resource
private IndexDao indexDao;


public List<User> getList(){


       return indexDao.getList();
}
}

创建service接口



import java.util.List;


import org.springframework.stereotype.Service;


import com.mx.model.User;


public interface IndexService {


public List<User> getList();


}

创建controller



import java.util.List;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import com.mx.model.User;
import com.mx.service.IndexService;




@Controller
@RequestMapping("/index")
public class IndexController {


@Resource
private IndexService indexService;

@RequestMapping("/test")
public String index(HttpServletRequest request,HttpServletResponse response){

List<User> list=indexService.getList();

request.setAttribute("user", list);
return "index1";
}
}

jsp接收参数:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<!-- el表达式接受list -->
<c:forEach items="${user}" var="user">
${user.id}
${user.username}
${user.password}
${user.type}
</c:forEach>
</body>
</html>


接着创建spring.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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        
        
        
        <!--引入缓存配置文件  -->
<bean id="propertiConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
<property name="locations">  
       <list>  
          <value>classpath:jdbc.properties</value>  
           <!--要是有多个配置文件,只需在这里继续添加即可 -->  
       </list>  
   </property>  
</bean>      
        <!-- 配置自动扫描的包 -->
        <mvc:annotation-driven/>
        <context:annotation-config />
        <context:component-scan base-package="com.mx"/>
</beans>
再创建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: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/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">


<!-- 默认扫描的包路径   这里扫描到controller-->  
   <context:component-scan base-package="com.mx.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>

<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>


</beans>
  接着是hibernate操作

 <?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd"
       default-autowire="byName" default-lazy-init="true">


    <!--配置hibernate数据源  我这里选用的是dbcp2.,其他的数据源,自己再去百度其他配置吧-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
          destroy-method="close" >


        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!--初始化连接池  设置连接数量初始值-->
        <property name="initialSize" value="3"/>

 <!--最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。-->
        <property name="maxIdle"  value="5"/>

<!--minIdle: 最小空闲连接-->
        <property name="minIdle" value="3"/>

   <!-- 最大链接数 -->  
        <property name="maxTotal" value="5"/>
    </bean>


    <!--hibernate session工厂-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
       <!--添加上面配置额数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置实体类-->
        <property name="packagesToScan">
            <list>
                <value>com.mx.model</value>
            </list>
        </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.current_session_context_class">thread</prop> -->
            </props>
        </property>
    </bean>


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


    <!-- 配置事务异常封装 -->
    <bean id="persistenceExceptionTranslationPostProcessor"
          class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    <!--  声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->
   <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="get*" propagation="REQUIRED" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>




  <aop:config expose-proxy="true">
      <!--   只对业务逻辑层实施事务 -->
        <aop:pointcut id="txPointcut" expression="execution(* com.mx.service..*.*(..))" />
        <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->
        <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
    </aop:config>
    <aop:aspectj-autoproxy proxy-target-class="true"/> 


<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
然后修改web.xml启动加载

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<!-- 这里具体不介绍了,你们应该明白,不明白下面留言-->
<web-app>
  <display-name>ssh</display-name>
   <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
  </context-param>
    <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>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  
  
  <servlet>
  <servlet-name>springDispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- 配置Spring mvc下的配置文件的位置和名称 -->
  <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>springDispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>
   <welcome-file-list>
    <welcome-file>/index</welcome-file>
  </welcome-file-list>
</web-app>
好了。搭建完成,注解不够详细,我找时间再改,搭建有问题可以留言。

项目运行看一下:


数据库对比


源码加数据库我放这了,自己多敲敲代码,对自己有好处。有问题欢迎交流。

http://pan.baidu.com/s/1jH8rC9o

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值