码迷,mamicode.com
首页 > 编程语言 > 详细

【Spring】SpringMVC整合JPA

时间:2016-05-12 18:52:00      阅读:736      评论:0      收藏:0      [点我收藏+]

标签:

这篇文章是在SpringMVC的基础上对数据持久层JPA的整合,实现了应用层和数据库的数据交互。在整合JPA前,请先参照下面第一篇博文搭建好SpringMVC框架。

一. 和本篇博文相关的一些基础知识请参考下面几篇博文:

  1. SpringMVC框架的搭建和配置详解请参考:http://blog.csdn.net/jianyuerensheng/article/details/51258942

  2. JPA的ORM框架原理介绍请参考:http://blog.csdn.net/jianyuerensheng/article/details/50804360

  3. JPA生命周期、映射关系详解请参考:http://blog.csdn.net/jianyuerensheng/article/details/50819155

二.JAP的配置过程:

项目整体结构如下:
技术分享
技术分享
1.在web.xml文件中进行配置

<!-- 引入 applicationContext.xml配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
    </context-param>
    <!-- 解决JPA因EntityManager关闭导致的延迟加载例外(异常) -->
    <filter>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

2. 添加Spring上下文配置文件applicationContext.xml.

<?xml version="1.0" encoding="UTF-8"  ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task  
        http://www.springframework.org/schema/task/spring-task-3.1.xsd  ">

    <context:component-scan base-package="com.zjn.service" />

    <bean id="configProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath*:META-INF/spring/*.properties</value>
            </list>
        </property>
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties"></property>
    </bean>

    <!-- 当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 
        Bean,当发现 Bean 中拥有@Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。 -->
    <bean
        class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

    <!-- Jpa 事务配置 -->
    <bean class="org.springframework.orm.jpa.JpaTransactionManager"
        id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <!--jpaVendorAdapter:指定实现JPA的适配器 -->
    <bean id="jpaVendorAdapter"
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="showSql" value="true" />
        <property name="database" value="${database}" />
        <property name="databasePlatform" value="org.hibernate.dialect.MySQLMyISAMDialect" />
    </bean>
    <!-- JPA实体管理工厂的配置 -->
    <bean
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        id="entityManagerFactory">
        <property name="persistenceUnitName" value="persistenceUnit" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${database.driverClassName}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" />
        <property name="testOnBorrow" value="true" />
        <property name="testOnReturn" value="true" />
        <property name="testWhileIdle" value="true" />
        <property name="timeBetweenEvictionRunsMillis" value="1800000" />
        <property name="numTestsPerEvictionRun" value="3" />
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        <property name="defaultAutoCommit" value="false" />
    </bean>

    <!-- Spring Data Jpa配置 -->
    <jpa:repositories base-package="com.zjn.repository"
        entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
</beans>


3. 添加JPA配置文件 persistence.xml。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="persistenceUnit"
        transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.jdbc.batch_size" value="30" />
            <property name="hibernate.use_sql_comments" value="true" />
            <!--自动输出schema创建DDL语句 -->
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
            <property name="hibernate.connection.charSet" value="UTF-8" />
        </properties>
    </persistence-unit>
</persistence>

4. 数据库配置文件 database.properties

database=MYSQL
database.url=jdbc:mysql://localhost:3306/spring?zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8&characterSetResults=UTF-8
database.username=root
database.password=smit0296139
database.driverClassName=com.mysql.jdbc.Driver

5.UserRepository.java

package com.zjn.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.zjn.entity.User;

public interface UserRepository extends JpaRepository<User, Long> {

    @Query("select u from User u where id = :id")
    public User findById(@Param("id") Long id);

    @Query("select u from User u ")
    public List<User> findAlls();

    @Query("select count(id) from User u ")
    public Long countId();

}

6.UserController.java

package com.zjn.controller;

import java.util.List;

import javax.annotation.Resource;

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

import com.zjn.entity.User;
import com.zjn.repository.UserRepository;

/**
 * 用户管理
 * 
 * @author zjn
 */
@Controller
public class UserController {
    @Autowired
    UserRepository userRepository;
    @RequestMapping("")
    public String Create(Model model) {
        return "create";
    }

    @RequestMapping("/save")
    public String Save(@ModelAttribute("form") User user, Model model) { // user:视图层传给控制层的表单对象;model:控制层返回给视图层的对象
        User user2 = userRepository.saveAndFlush(user);
        model.addAttribute("user", user2);
        return "detail";
    }
}

7.运行结果
初始化界面:
技术分享
输入内容:
技术分享
点击创建运行结果:
技术分享

【Spring】SpringMVC整合JPA

标签:

原文地址:http://blog.csdn.net/jianyuerensheng/article/details/51352184

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!