您的位置:首页 > 编程语言 > Java开发

spring+springmvc+hibernate整合

2017-11-20 18:13 513 查看
我看了下很多楼主的博客,写的东西毕竟不是很适合自己所想要的;我这里边通透的讲解及说下

我先说由配置再到代码(我把hibernate的配置和spring的配置整合在一起的 尽量做到零配置 我把相关的配置都放在src/config包下的 你看下配置的代码 你应该就看出来啦)

第一个便是web.项目里配置

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  <display-name>spring-mvc</display-name>

   <!--   配置spring相关配置 --> 

  <context-param>  

        <param-name>contextConfigLocation</param-name>  

        <param-value>classpath*:config/springAnnotation-core.xml</param-value>  

        <!-- <param-value>classpath*:config/springAnnotation-servlet.xml</param-value> -->  

  </context-param>

  

  <!--   配置spring启动listener入口 -->  

  <listener>

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

  </listener>

   <!-- 配置springMVC启动DispatcherServlete入口 --> 

  <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*:config/applicationContext-mvc.xml</param-value>

    </init-param>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>springmvc</servlet-name>

    <url-pattern>*.do</url-pattern>

  </servlet-mapping>

</web-app>

接下来是springmvc的xml文件springAnnotation-core.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:tx="http://www.springframework.org/schema/tx"  

    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-3.2.xsd   

    http://www.springframework.org/schema/tx   

    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  

    http://www.springframework.org/schema/context  

    http://www.springframework.org/schema/context/spring-context-3.2.xsd  

    http://www.springframework.org/schema/mvc  

    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  

  

    <!-- 自动扫描controller的包名  我这里做了下通配符 -->  

     <context:component-scan base-package="com.**.controllers"/>

  

    <!-- 默认的注解映射的支持,自动注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->  

    <mvc:annotation-driven />  

  

    <!-- 视图解析器  通过controller返回的值 判断跳转到那个页面去-->  

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  

        <property name="prefix" value="/"/>  

        <property name="suffix" value=".jsp"/>  

        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  

    </bean>

</beans>

接下来是spring+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:jaxws="http://cxf.apache.org/jaxws"

       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-4.1.xsd

       http://www.springframework.org/schema/tx  

       http://www.springframework.org/schema/tx/spring-tx-4.1.xsd

       http://www.springframework.org/schema/aop  

       http://www.springframework.org/schema/aop/spring-aop-4.1.xsd

       http://www.springframework.org/schema/context  

       http://www.springframework.org/schema/context/spring-context-4.1.xsd

       http://cxf.apache.org/jaxws 

       http://cxf.apache.org/schemas/jaxws.xsd">  

       

<!-- 引入properties文件 -->

    <context:property-placeholder location="classpath*:/config/appConfig.properties" />

      

    <!-- 定义数据库连接池数据源bean destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

        destroy-method="close">

        <!-- 设置JDBC驱动名称 -->

        <property name="driverClass" value="${jdbc.Adriver}" />

        <!-- 设置JDBC连接URL -->

        <property name="jdbcUrl" value="${jdbc.Aurl}" />

        <!-- 设置数据库用户名 -->

        <property name="user" value="${jdbc.Ausername}" />

        <!-- 设置数据库密码 -->

        <property name="password" value="${jdbc.Apassword}" />

        <property name="maxPoolSize" value="20"></property>  

       <!-- 设置数据库连接池的最小连接数 -->  

       <property name="minPoolSize" value="5"></property>  

       <!-- 设置数据库连接池的初始化连接数 -->  

       <property name="initialPoolSize" value="5"></property>     

       <!--最大空闲时间,300秒内未使用则连接被丢弃。若为0则永不丢弃。-->    

        <property name="maxIdleTime">    

            <value>300</value>    

        </property>    

       <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。-->    

        <property name="acquireIncrement">    

            <value>5</value>    

        </property>    

    </bean>

    

    <!-- 配置sessionFactory -->

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <!-- 数据源 -->

        <property name="dataSource" ref="dataSource" />

       <!--满足注解实体类  -->

        <property name="packagesToScan" value="com.azj.entity" />

        <!-- hibernate的相关属性配置 -->

        <property name="hibernateProperties">

            <value>

                <!-- 设置数据库方言 -->

                hibernate.dialect=org.
4000
hibernate.dialect.MySQLDialect

                <!-- 设置自动创建|更新|验证数据库表结构 -->

                hibernate.hbm2ddl.auto=update

                <!-- 是否在控制台显示sql -->

                hibernate.show_sql=false

                <!-- 是否格式化sql,优化显示 -->

                hibernate.format_sql=true

                <!-- 是否开启二级缓存 -->

                hibernate.cache.use_second_level_cache=false

                <!-- 是否开启查询缓存 -->

                hibernate.cache.use_query_cache=false

                <!-- 数据库批量查询最大数 -->

                hibernate.jdbc.fetch_size=50

                <!-- 数据库批量更新、添加、删除操作最大数 -->

                hibernate.jdbc.batch_size=50

                <!-- 是否自动提交事务 -->

                hibernate.connection.autocommit=true

                <!-- 指定hibernate在何时释放JDBC连接 -->

                hibernate.connection.release_mode=auto

                <!-- 创建session方式 hibernate4.x 的方式 -->

                hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

                <!-- javax.persistence.validation.mode默认情况下是auto的,就是说如果不设置的话它是会自动去你的classpath下面找一个bean-validation**包 

                    所以把它设置为none即可 -->

                javax.persistence.validation.mode=none

            </value>

        </property>

    </bean>

    <!-- 定义事务管理 -->

    <bean id="transactionManager"

        class="org.springframework.orm.hibernate4.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory" />

    </bean>

    

    <!-- 扫描有注解的文件  base-package 包路径 -->

    <!-- <context:component-scan base-package="com.*"/> -->

    <context:component-scan base-package="com.azj.*">

           <!-- //扫描时跳过 @Controller 注解的JAVA类(控制器) 就是springmvc的自动扫描注解包 -->

            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

        </context:component-scan>

    

    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>

            <!-- 事务执行方式

                REQUIRED:指定当前方法必需在事务环境中运行,

                如果当前有事务环境就加入当前正在执行的事务环境,

                如果当前没有事务,就新建一个事务。

                这是默认值。 

             -->

            <tx:method name="create*" propagation="REQUIRED" />

            <tx:method name="save*" propagation="REQUIRED" />

            <tx:method name="add*" propagation="REQUIRED" />

            <tx:method name="update*" propagation="REQUIRED" />

            <tx:method name="remove*" propagation="REQUIRED" />

            <tx:method name="del*" propagation="REQUIRED" />

            <tx:method name="import*" propagation="REQUIRED" />

            <!-- 

                指定当前方法以非事务方式执行操作,如果当前存在事务,就把当前事务挂起,等我以非事务的状态运行完,再继续原来的事务。 

                查询定义即可

                read-only="true"  表示只读

             -->

            <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />

        </tx:attributes>

    </tx:advice>

    <!-- 定义切面,在 com.azj.*.dao.*Dao.*(..)中执行有关的hibernate session的事务操作 -->

    <aop:config>

        <aop:pointcut id="serviceOperation" expression="execution(* com.azj.dao.*Dao.*(..))" />

        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />

    </aop:config>

    

</beans>

 然后就是相关配置连接的设置appConfig.properties:

jdbc.Adriver=com.mysql.jdbc.Driver

jdbc.Aurl=jdbc:mysql://localhost:3306/azj?useUnicode=true&characterEncoding=UTF-8

jdbc.Ausername=root

jdbc.Apassword=root

接下来便是控制层到service层再到Dao层的编码:内容比较简明 添加些代码便可深入 我这里不多说

控制层的包名com.azj.controllers 类名:azjController 编码:

package com.azj.controllers;

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

import org.springframework.stereotype.Controller;

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

import com.azj.service.userService;

@Controller

@RequestMapping("/azj")

public class azjController {

        //service层的注解
@Autowired
private userService userservice;

@RequestMapping("tospring")
public void toSpring(){
System.out.println("-----------start---------");
System.out.println(userservice.getUser());
}

}

service层之接口

包名:com.azj.service 类名:userService 编码:

package com.azj.service;

public interface userService {

public String getUser();

}

service层之实现类

包名:com.azj.serviceImpl类名:userServiceImpl 编码:

package com.azj.serviceImpl;

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

import org.springframework.stereotype.Service;

import com.azj.dao.UserDao;

import com.azj.service.userService;

@Service

public class userServiceImpl implements userService{

@Autowired

private UserDao userdao;

@Override
public String getUser() {
return userdao.getUser();

}

}

dao层之接口

包名:com.azj.dao 类名:UserDao

编码:

package com.azj.dao;

public interface UserDao {
public String getUser();

}

Dao层之实现类

包名:com.azj.daoImpl 类名UserDaoImpl

编码:

package com.azj.daoImpl;

import org.hibernate.Session;

import org.springframework.stereotype.Repository;

import com.azj.dao.UserDao;

import com.azj.entity.Person;

import com.azj.entity.User;

import utils.baseUtils;

@Repository

public class UserDaoImpl extends baseUtils implements UserDao{
@Override
public String getUser() {

Session s=getSession();
User u=new User();
u.setUsername("admin");
u.setPassword("123456");
s.save(u);
flush();
return "集成 ok";

}

}

工具类baseUtils :

编码:

package utils;

import javax.annotation.Resource;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

public class baseUtils {
/*ServiceRegistry是Hibernate4.X新增接口, 

    应用于Hibernate的配置或者服务等将统一向这个ServiceRegistry注册后才能生效。 

    所以需要构建一个ServiceRegistry对象,将配置信息向它注册,然后Configuration对象根据从这个ServiceRegistry对象中获取配置信息生成SessionFactory。 

 Hibernate4的配置入口不再是Configuration对象,而是ServiceRegistry对象,Configuration对象将通过ServiceRegistry对象获取配置信息。 

 hibernate4 源码位置:org.hibernate.service.ServiceRegistryBuilder    具体可参看hibernate源码。以及API*/  

@Resource

  protected  SessionFactory sessionFactory;
@SuppressWarnings("rawtypes")
public static final ThreadLocal session =new ThreadLocal();  //用ThreadLocal模式 (线程局部变量模式) 管理Session
   public   Session getSession()
   { 
    Session s=(Session) session.get();
    if(s==null){
    s=sessionFactory.getCurrentSession();
    }
   
       return s;
   }
   
   public  void flush() {
       getSession().flush();
   }

   public  void clear() {
       getSession().clear();
   }

}

实体类及相关注解:

包下:com.azj.entity

package com.azj.entity;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

@Entity

//对应数据库的表名

@Table(name="y_user")

public class User {
private int userid ;
private String username;
private String password;

@Id//定义为数据库的主键ID  (建议不要在属性上引入注解,因为属性是private的,如果引入注解会破坏其封装特性,所以建议在getter方法上加入注解)
@GeneratedValue//自动增长
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
//对应的表                           是否为空                 避免同一字段的重复添加updatable=false,  字节长度
@Column(name="username",nullable = false,length = 20)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name="password",nullable = false,length = 20)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

这里采用的自动建表及数据的插入;

项目地址http://download.csdn.net/download/rainjm/10154068

以上便是全部内容 仅供参考
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring+springmvc+hib