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. 宏os_file_read_func

    # define os_file_read(file, buf, offset, offset_high, n) \ os_file_read_func(file, buf, offset, offs ...

  2. WDF模型驱动程序开发

    WDF驱动程序开发 1. 引言 设备驱动程序是硬件设备连接到计算机系统的软件接口,任何设备都必须有相应的驱动程序才能在计算机系统上正常工作.设备驱动程序的优劣直接关系到整个系统的性能和稳定性,因此,设 ...

  3. Android Configuration change引发的问题及解决方法(转)

    之前在学习Fragment和总结Android异步操作的时候会在很多blog中看到对Configuration Change的讨论,以前做的项目都是固定竖屏的,所以对横竖屏切换以及横竖屏切换对程序有什 ...

  4. <十一>面向对象分析之UML核心元素之组件

    组件

  5. MySQL row模式binlog复制原理

    http://www.360doc.com/content/14/1107/14/12904276_423333021.shtml

  6. TeamViewer

    TeamViewer远程连接非常好用

  7. hdu 2473 Junk-Mail Filter(并查集_虚节点)2008 Asia Regional Hangzhou

    感觉有些难的题,刚开始就想到了设立虚节点,但是实现总是出错,因为每次设立了虚节点之后,无法将原节点和虚节点分开,导致虚节点根本无意义. 以上纯属废话,可以忽略…… 题意—— 给定n个点(0, 1, 2 ...

  8. ZOJ3865:Superbot(BFS) The 15th Zhejiang University Programming Contest

    一个有几个小坑的bfs 题目很长,但并不复杂,大概总结起来有这么点. 有t组输入 每组输入n, m, p.表示一个n*m的地图,每p秒按键会右移一次(这个等会儿再讲). 然后是地图的输入.其中'@'为 ...

  9. Codeforces Round #361 (Div. 2) 套题

    A - Mike and Cellphone 问有没有多解,每个点按照给出的序列用向量法跑一遍 #include<cstdio> #include<cstring> #incl ...

  10. 用VBS脚本发邮件

    需求是这样的:针对账号的管理,如果发现该账号的管理员给账号加了批注,(比如要过期,修改密码,完善资料等),就需要找到这样的账号及其管理的邮件,然后发邮件给他们的管理员同时抄送给账号以达到提醒的目的.那 ...