spring+springmvc+hibernate整合

我看了下很多樓主的博客,寫的東西畢竟不是很適合自己所想要的;我這裏邊通透的講解及說下


我先說由配置再到代碼(我把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.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

以上便是全部內容 僅供參考


發佈了54 篇原創文章 · 獲贊 19 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章