Spring Data JPA项目旨在简化基于仓库的JPA的创建并减少与数据库交互的所需的代码量。本人在自己的工作和个人爱好项目中已经使用一段时间,它却是是事情如此简单和清洗,现在是时候与你分享我的知识。

本文是我的Spring Data JPA教程的第一部分,将向你描述的是,当你使用Hibernate作为你的jpa提供者时怎样配置Spring Data JPA,在我们开始之前,首先应该明白一件事情,本教程不是Hibernate, JPA 或 Spring的人们教程,如果你想理解在我的Spring Data JPA教程中描述的概念,你必须有关于这些技术方面的经验

本教程的依赖如下:

  • BoneCP 0.7.1.RELEASE (同样你也可以采用其他的数据源实现)
  • Hibernate 4.0.1.Final
  • Spring Framework 3.1.0.RELEASE
  • Spring Data JPA 1.0.2
  • Servlet API 3.0

当然,既然本人使用Maven作为构建工具,如果你想运行我的example应用你必须安装它。

开始

现在开始了. 你可以通过如下步骤配置Spring Data JPA:

  • 获取必须的依赖.
  • 在Spring application context configuration里面配置必须的bean. Spring Data JPA需要的bean是: 数据源, 事务管理器 和 实体管理工厂.
  • 配置Spring Data JPA.

这些步骤在下面详细解释:

获取必须的依赖

首先,你需要获取必须的依赖,你可以通过在你的pom.xml文件里面配置这些依赖,我的example的pom.xml如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.petrikainulainen.spring</groupId>
<artifactId>data-jpa-tutorial-part-one</artifactId>
<packaging>war</packaging>
<version>0.1</version>
<name>Spring Data JPA Tutorial Part One</name>
<description>Spring Data JPA Tutorial Part One</description>
<licenses>
<license>
<name>Apache License 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0</url>
</license>
</licenses>
<url>http://www.petrikainulainen.net</url>
<repositories>
<repository>
<id>repository.jboss.org-public</id>
<name>JBoss repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public</url>
</repository>
</repositories>
<properties>
<hibernate.version>4.0.1.Final</hibernate.version>
<mysql.connector.version>5.1.18</mysql.connector.version>
<slf4j.version>1.6.1</slf4j.version>
<spring.version>3.1.0.RELEASE</spring.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.160</version>
</dependency>
<!-- MySQL JDBC connector -->
<!-- If you want to use MySQL, uncomment this dependency declation. -->
<!--
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
-->
<!-- PostgreSQL JDBC 4 -->
<!-- If you don't want to use PostgreSQL, uncomment this dependency declaration. -->
<!--
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
</dependency>
-->
<!-- BoneCP -->
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
<version>0.7.1.RELEASE</version>
</dependency>
<!-- Servlet API 3.0 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Logging dependencies -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- Testing Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>data-jpa-tutorial-part-one</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.0.RC2</version>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<webAppConfig>
<defaultsDescriptor>src/main/resources/webdefault.xml</defaultsDescriptor>
</webAppConfig>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.0</version>
<configuration>
<reportPlugins>
<!-- Cobertura Plugin -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.1</version>
</plugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
</project>

配置 Spring应用上下文

第二步,你必须配置Spring应用上下文,也许您还记得,你需要配置数据源,事务管理器和实体管理器工厂的bean。如果您正在使用Spring 3.1和Servlet 3.0,你可以这样做到,通过实现一个Java配置类,并在您的Web应用程序初始化的时候加载该配置类。我的应用程序上下文配置类的内容如下下:

import com.jolbox.bonecp.BoneCPDataSource;
import org.hibernate.ejb.HibernatePersistence;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; import javax.annotation.Resource;
import javax.sql.DataSource; /**
* An application context Java configuration class. The usage of Java configuration
* requires Spring Framework 3.0 or higher with following exceptions:
* <ul>
* <li>@EnableWebMvc annotation requires Spring Framework 3.1</li>
* </ul>
* @author Petri Kainulainen
*/
@Configuration
@ComponentScan(basePackages = {"net.petrikainulainen.spring.datajpa.controller"})
@EnableWebMvc
@ImportResource("classpath:applicationContext.xml")
@PropertySource("classpath:application.properties")
public class ApplicationContext { private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/jsp/";
private static final String VIEW_RESOLVER_SUFFIX = ".jsp"; private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username"; private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan"; private static final String PROPERTY_NAME_MESSAGESOURCE_BASENAME = "message.source.basename";
private static final String PROPERTY_NAME_MESSAGESOURCE_USE_CODE_AS_DEFAULT_MESSAGE = "message.source.use.code.as.default.message"; @Resource
private Environment environment; @Bean
public DataSource dataSource() {
BoneCPDataSource dataSource = new BoneCPDataSource(); dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD)); return dataSource;
} @Bean
public JpaTransactionManager transactionManager() throws ClassNotFoundException {
JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject()); return transactionManager;
} @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class); Properties jpaProterties = new Properties();
jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL)); entityManagerFactoryBean.setJpaProperties(jpaProterties); return entityManagerFactoryBean;
} @Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename(environment.getRequiredProperty(PROPERTY_NAME_MESSAGESOURCE_BASENAME));
messageSource.setUseCodeAsDefaultMessage(Boolean.parseBoolean(environment.getRequiredProperty(PROPERTY_NAME_MESSAGESOURCE_USE_CODE_AS_DEFAULT_MESSAGE))); return messageSource;
} @Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX); return viewResolver;
}
}

我的web应用初始器如下:

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.*; /**
* Web application Java configuration class. The usage of web application
* initializer requires Spring Framework 3.1 and Servlet 3.0.
* @author Petri Kainulainen
*/
public class DataJPAExampleInitializer implements WebApplicationInitializer { private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
private static final String DISPATCHER_SERVLET_MAPPING = "/"; @Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ApplicationContext.class); ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING); servletContext.addListener(new ContextLoaderListener(rootContext));
}
}

你可能注意到,本人使用@PropertySource annotation来标识属性文件的位置,属性文件包含了使用的配置参数的值,myapplication.properties文件内容如下:

# The default database is H2 memory database but I have also
# added configuration needed to use either MySQL and PostgreSQL. #Database Configuration
db.driver=org.h2.Driver
#db.driver=com.mysql.jdbc.Driver
#db.driver=org.postgresql.Driver
db.url=jdbc:h2:mem:datajpa
#db.url=jdbc:mysql://localhost:3306/datajpa
#db.url=jdbc:postgresql://localhost/datajpa
db.username=sa
db.password= #Hibernate Configuration
hibernate.dialect=org.hibernate.dialect.H2Dialect
#hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.format_sql=true
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.show_sql=true #MessageSource
message.source.basename=i18n/messages
message.source.use.code.as.default.message=true #EntityManager
#Declares the base package of the entity classes
entitymanager.packages.to.scan=net.petrikainulainen.spring.datajpa.model

配置Spring Data JPA

第三步,你必须配置Spring Data JPA,如果你留心,你可能已经注意到,本人在我的应用上下文配置类使用@ImportResource annotation 来从xml配置文件导入额外的配置. 当前Spring Data JPA不支持java配置,因此,唯一的方式是使用XML配置文件,我的applicationContext.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!--
Configures the location of static resources such as css files.
Requires Spring Framework 3.0 or higher.
-->
<mvc:resources mapping="/static/**" location="/static/"/> <!--
Ensures that dispatcher servlet can be mapped to '/' and static resources
are still served by the containers default servlet. Requires Spring Framework
3.0 or higher.
-->
<mvc:default-servlet-handler/> <!--
Configures Spring Data JPA and sets the base package of my DAOs.
-->
<jpa:repositories base-package="net.petrikainulainen.spring.datajpa.repository"/>
</beans>

You Are Done

本文介绍内容:我现在已经向你演示了如何配置Spring Data JPA。同时也创建了一个示例应用程序来演示配置的实际运行。你可以通过从Github获取我的示例应用程序来测试自己的配置,并通过使用Maven Jetty plugin来运行这个示例web应用(:请记住,首先创建模型和仓库的package。既然不可能向Git暂存区域添加空目录,Github仓库也不具有它们)。

我的Spring Data JPA教程的第二部分介绍了如何通过使用Spring  Data JPA创建一个简单的CRUD Web应用程序。敬请关注。

---------------------------------------------------------------------------

本系列Spring Data JPA 教程翻译系本人原创

作者 博客园 刺猬的温驯

本文链接 http://www.cnblogs.com/chenying99/archive/2013/06/19/3143516.html

本文版权归作者所有,未经作者同意,严禁转载及用作商业传播,否则将追究法律责任。

Spring Data JPA教程,第一部分: Configuration(翻译)的更多相关文章

  1. Spring Data JPA 教程(翻译)

    写那些数据挖掘之类的博文 写的比较累了,现在翻译一下关于spring data jpa的文章,觉得轻松多了. 翻译正文: 你有木有注意到,使用Java持久化的API的数据访问代码包含了很多不必要的模式 ...

  2. Spring Data JPA教程, 第三部分: Custom Queries with Query Methods(翻译)

    在本人的Spring Data JPA教程的第二部分描述了如何用Spring Data JPA创建一个简单的CRUD应用,本博文将描述如何在Spring Data JPA中使用query方法创建自定义 ...

  3. Spring Data JPA教程, 第二部分: CRUD(翻译)

    我的Spring Data Jpa教程的第一部分描述了,如何配置Spring Data JPA,本博文进一步描述怎样使用Spring Data JPA创建一个简单的CRUD应用.该应用要求如下: pe ...

  4. Spring Data JPA教程, 第八部分:Adding Functionality to a Repository (未翻译)

    The previous part of my tutorial described how you can paginate query results with Spring Data JPA. ...

  5. Spring Data JPA教程, 第五部分: Querydsl(未翻译)

    The fourth part of my Spring Data JPA tutorialdescribed how you can implement more advanced queries ...

  6. Spring Data JPA教程, 第七部分: Pagination(未翻译)

    The previous part of my Spring Data JPA tutorialdescribed how you can sort query results with Spring ...

  7. Spring Data JPA教程, 第六部分: Sorting(未翻译)

    The fifth part of my Spring Data JPA tutorialdescribed how you can create advanced queries with Spri ...

  8. Spring Data JPA教程, 第四部分: JPA Criteria Queries(未翻译)

    The third part of my Spring Data JPA tutorialdescribed how you can create custom queries by using qu ...

  9. Spring Data JPA(官方文档翻译)

    关于本书 介绍 关于这本指南 第一章 前言 第二章 新增及注意点 第三章 项目依赖 第四章 使用Spring Data Repositories 4.1 核心概念 4.2 查询方法 4.3 定义rep ...

随机推荐

  1. JSOI2015 分组赛记

    分组赛结束了,虽然跟我关系不大,但是去了还是学到了不少东西 day1 上午报到,在宾馆遇到大神wzy,orz 好像没有参赛证发了,于是给我发了一个[工作证],233我是工作人员了,高贵冷艳 下午是常中 ...

  2. C#手动回收内存的简单方法

    C#有自动回收内存的机制,但是有时自动回收有一定滞后,需要在变量使用后迅速回收,节约内存,这里介绍一个最简单的方法. 1.先对对象赋值 null; 2.System.GC.Collect(); 代码样 ...

  3. Google发布SSLv3漏洞简要分析报告

    今天上午,Google发布了一份关于SSLv3漏洞的简要分析报告.根据Google的说法,该漏洞贯穿于所有的SSLv3版本中,利用该漏洞,黑客可以通过中间人攻击等类似的方式(只要劫持到的数据加密两端均 ...

  4. Java Web编程的主要组件技术——Servlet

    参考书籍:<J2EE开源编程精要15讲> Servlet是可以处理客户端传来的HTTP请求,并返回响应,由服务器端调用执行,有一定编写规范的Java类. 例如: package test; ...

  5. BZOJ 1861 书架

    (╯-_-)╯╧╧ 此处为错误代码. #include<iostream> #include<cstdio> #include<cstring> #include& ...

  6. phonegap archive 报错 Cordova/CDVViewController.h' file not found

    在BuildSettings->Header Search Paths  增加如下路径,问题解决 $(OBJROOT)/UninstalledProducts/include "$(O ...

  7. UVA 1001 Say Cheese 奶酪里的老鼠(最短路,floyd)

    题意:一只母老鼠想要找到她的公老鼠玩具(cqww?),而玩具就丢在一个广阔的3维空间(其实可以想象成平面)上某个点,而母老鼠在另一个点,她可以直接走到达玩具的位置,但是耗时是所走过的欧几里得距离*10 ...

  8. noip2007提高组题解

    题外话:这一年的noip应该是最受大众关心的,以至于在百度上输入noip第三个关键字就是noip2007.主要是由于这篇文章:http://www.zhihu.com/question/2110727 ...

  9. [转] ArcGIS engine中气泡标注的添加、修改

    小生 原文 ArcGIS engine中气泡标注的添加.修改! 你微微地笑着,不同我说什么话.而我觉得,为了这个,我已等待得久了.                                   ...

  10. ylbtech-SubwayNav(地铁线路导航)-数据库设计

    ylbtech-DatabaseDesgin:ylbtech-SubwayNav(地铁线路导航)-数据库设计 DatabaseName:SubwayNav(地铁线路导航) Type:线路导航 1.A, ...