springmvc+springjpa+hibernate整合簡例

1、例子下載地址

代碼下載地址


2、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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>springmvc</display-name>
  
  
  <!-- Spring-MVC的請求轉發器 -->
  <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:springmvc-servlet.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配置 -->   
  <listener>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  </listener> 
  <!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->  
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.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> 


  <!-- 解決spring data jpa 事務懶加載 -->  
  <filter>  
      <filter-name>openEntityManagerInViewFilter</filter-name>  
      <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>  
  </filter>  
  <filter-mapping>  
      <filter-name>openEntityManagerInViewFilter</filter-name>  
      <url-pattern>/*</url-pattern>  
  </filter-mapping> 
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3、springmvc-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc
	   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	   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">

<!--  
	當映射爲@RequestMapping("/user/add")時:
	1、攔截*.do,例如:/user/add.do,弊端:所有的url都要以.do結尾。不會影響訪問靜態文件。
	2、攔截/app/*,例如:/app/user/add,弊端:請求的url都要包含/app,@RequestMapping("/user/add")中不須要包含/app。
	3、攔截/,例如:/user/add,弊端:對jpg,js,css靜態文件的訪問也被攔截不能正常顯示。後面有解決辦法。
	4、攔截/*,可以走到Action中,但轉發到jsp時再次被攔截,不能訪問到jsp。
-->

	<!-- 掃描web包,應用Spring的註解 -->
	<context:component-scan base-package="com.springmvc.test.controller"/>
	
	<!-- 會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,
	是spring MVC爲@Controllers分發請求所必須的。 -->
    <mvc:annotation-driven /> 

   
	<!-- 配置視圖解析器,將ModelAndView及字符串解析爲具體的頁面 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:viewClass="org.springframework.web.servlet.view.JstlView" 
		p:prefix="/WEB-INF/jsp/"
		p:suffix=".jsp" />

     <!-- 對靜態資源文件的訪問  方案一 (二選一)  
    <mvc:default-servlet-handler/>  
     -->
       
    <!-- 對靜態資源文件的訪問  方案二 (二選一) -->
	<mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>  
	<mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>  
	<mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>   
     
</beans>

4、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:jpa="http://www.springframework.org/schema/data/jpa"
				xmlns:tx="http://www.springframework.org/schema/tx"
				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.xsd
				http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

		<!-- spring掃描的路徑 爲了使用註解-->
 		<context:component-scan base-package="com.springmvc.test"/>
 	
		<!-- 定義實體管理器工廠 -->
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
             <property name="persistenceUnitName" value="myJPA"/>
        </bean>
         
        <!-- 配置事務管理器 -->  
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">  
            <property name="entityManagerFactory" ref="entityManagerFactory" />  
        </bean> 
       
        <!-- 啓用 annotation事務--> 
        <tx:annotation-driven transaction-manager="transactionManager"/> 
           
        <!-- 配置Spring Data JPA掃描目錄--> 
        <jpa:repositories base-package="com.springmvc.test.repository"/>
</beans>

5、persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
            http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
            
    <persistence-unit name="myJPA" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>  
        <properties>
            <!--配置Hibernate方言 -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
            <!--配置數據庫驅動 -->
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
            <!--配置數據庫用戶名 -->
            <property name="hibernate.connection.username" value="root" />
            <!--配置數據庫密碼 -->
            <property name="hibernate.connection.password" value="123456" />
            <!--配置數據庫url -->
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
            <!--設置外連接抓取樹的最大深度 -->
            <property name="hibernate.max_fetch_depth" value="3" />
            <!--自動輸出schema創建DDL語句 -->
            <property name="hibernate.hbm2ddl.auto" value="update" />    
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="javax.persistence.validation.mode" value="none"/>
        </properties>
    </persistence-unit>
</persistence>

6、目錄結構


7、基本類

(1)Person

package com.springmvc.test.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 
 * @author xuzebin
 *
 */
@Entity
@Table(name="person")
public class Person implements Serializable{
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Integer id;
	private String name;
	private Integer age;
	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 Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Person [id=");
		builder.append(id);
		builder.append(", name=");
		builder.append(name);
		builder.append(", age=");
		builder.append(age);
		builder.append("]");
		return builder.toString();
	}

}

(2)PersonRepository

package com.springmvc.test.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.springmvc.test.entity.Person;
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {

}

(3)PersonManager

package com.springmvc.test.service;

import com.springmvc.test.entity.Person;

/**
 * 
 * @author xuzebin
 *
 */
public interface PersonManager {
	public void save(Person p);
}

(4)PersonManagerImpl

package com.springmvc.test.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.springmvc.test.entity.Person;
import com.springmvc.test.repository.PersonRepository;
import com.springmvc.test.service.PersonManager;
/**
 * 
 * @author xuzebin
 *
 */
@Service("personManager")
public class PersonManagerImpl implements PersonManager {
	@Autowired
	private PersonRepository personRepository;
	
	public void save(Person p) {
		personRepository.save(p);
	}

}

(5)TestController

package com.springmvc.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springmvc.test.entity.Person;
import com.springmvc.test.repository.PersonRepository;
import com.springmvc.test.service.PersonManager;
import com.springmvc.test.util.TestUtil;

/**
 * 
 * @author xuzebin
 *
 */
@Controller
@RequestMapping("/test")
public class TestController {
	@Autowired
	private TestUtil testUtil;
	@Autowired
	private PersonManager personManager;
	
	@RequestMapping("/show")
	public String show(){
		System.out.println(testUtil.say());
		Person p=new Person();
		p.setName("xzb");
		p.setAge(25);
		personManager.save(p);
		return "test";
	}

}

8、參考原博客地址

原文地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章