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
本文版權歸作者所有,未經作者同意,嚴禁轉載及用作商業傳播,否則將追究法律責任。