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、参考原博客地址

原文地址

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值