湖北金扬建设网站,各种网站开发工具,增城高端定制网站建设,湖北省住房建设部官方网站Spring Data JPA是一个旨在简化基于JPA的存储库的创建并减少与数据库通信所需的代码量的项目。 在我的工作和个人爱好项目中#xff0c;我已经使用了一段时间#xff0c;确实使事情变得更加简单和整洁。 现在是时候与您分享我的知识了。 这是我的Spring Data JPA教程的第一部… Spring Data JPA是一个旨在简化基于JPA的存储库的创建并减少与数据库通信所需的代码量的项目。 在我的工作和个人爱好项目中我已经使用了一段时间确实使事情变得更加简单和整洁。 现在是时候与您分享我的知识了。 这是我的Spring Data JPA教程的第一部分它将向您介绍在将Hibernate用作JPA提供程序时如何配置Spring Data JPA。 在开始之前我想弄清楚一件事本教程不是HibernateJPA或Spring的入门级教程。 如果您想了解我的Spring Data JPA教程中描述的概念那么您必须对这些技术有一定的经验。 本教程的依赖性如下 BoneCP 0.7.1.RELEASE您也可以使用其他数据源实现 Hibernate 4.0.1.Final Spring Framework 3.1.0。发布 Spring Data JPA 1.0.2 Servlet API 3.0 另外由于我将Maven用作构建工具因此如果要运行示例应用程序则必须安装它。 入门 现在该开始了。 您可以按照以下步骤配置Spring Data JPA 您必须获得所需的依赖关系。 您必须在Spring应用程序上下文配置中配置所需的bean。 Spring Data JPA所需的bean是数据源事务管理器和实体管理器工厂。 您必须配置Spring Data JPA。 以下将详细解释这些步骤 获得所需的辅佐 首先您需要获取所需的依赖关系。 您可以通过在pom.xml文件中配置所需的依赖项来实现。 我的示例的pom.xml看起来如下 project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsdmodelVersion4.0.0/modelVersiongroupIdnet.petrikainulainen.spring/groupIdartifactIddata-jpa-tutorial-part-one/artifactIdpackagingwar/packagingversion0.1/versionnameSpring Data JPA Tutorial Part One/namedescriptionSpring Data JPA Tutorial Part One/descriptionlicenseslicensenameApache License 2.0/nameurlhttp://www.apache.org/licenses/LICENSE-2.0/url/license/licensesurlhttp://www.petrikainulainen.net/urlrepositoriesrepositoryidrepository.jboss.org-public/idnameJBoss repository/nameurlhttps://repository.jboss.org/nexus/content/groups/public/url/repository/repositoriespropertieshibernate.version4.0.1.Final/hibernate.versionmysql.connector.version5.1.18/mysql.connector.versionslf4j.version1.6.1/slf4j.versionspring.version3.1.0.RELEASE/spring.versionproject.build.sourceEncodingUTF-8/project.build.sourceEncoding/propertiesdependencies!-- Spring Framework --dependencygroupIdorg.springframework/groupIdartifactIdspring-beans/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-core/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-context-support/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-jdbc/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-orm/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-tx/artifactIdversion${spring.version}/version/dependency!-- Spring MVC --dependencygroupIdorg.springframework/groupIdartifactIdspring-web/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-webmvc/artifactIdversion${spring.version}/version/dependencydependencygroupIdcglib/groupIdartifactIdcglib/artifactIdversion2.2.2/version/dependency!-- Spring Data JPA --dependencygroupIdorg.springframework.data/groupIdartifactIdspring-data-jpa/artifactIdversion1.0.2.RELEASE/version/dependency!-- Hibernate --dependencygroupIdorg.hibernate/groupIdartifactIdhibernate-core/artifactIdversion${hibernate.version}/version/dependencydependencygroupIdorg.hibernate/groupIdartifactIdhibernate-entitymanager/artifactIdversion${hibernate.version}/version/dependency!-- H2 Database --dependencygroupIdcom.h2database/groupIdartifactIdh2/artifactIdversion1.3.160/version/dependency!-- MySQL JDBC connector --!-- If you want to use MySQL, uncomment this dependency declation. --!--dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion${mysql.connector.version}/version/dependency--!-- PostgreSQL JDBC 4 --!-- If you dont want to use PostgreSQL, uncomment this dependency declaration. --!--dependencygroupIdpostgresql/groupIdartifactIdpostgresql/artifactIdversion9.0-801.jdbc4/version/dependency--!-- BoneCP --dependencygroupIdcom.jolbox/groupIdartifactIdbonecp/artifactIdversion0.7.1.RELEASE/version/dependency!-- Servlet API 3.0 --dependencygroupIdjavax.servlet/groupIdartifactIdjavax.servlet-api/artifactIdversion3.0.1/versionscopeprovided/scope/dependencydependencygroupIdjavax.servlet/groupIdartifactIdjstl/artifactIdversion1.2/version/dependency!-- Logging dependencies --dependencygroupIdorg.slf4j/groupIdartifactIdslf4j-api/artifactIdversion${slf4j.version}/version/dependencydependencygroupIdorg.slf4j/groupIdartifactIdslf4j-log4j12/artifactIdversion${slf4j.version}/version/dependencydependencygroupIdlog4j/groupIdartifactIdlog4j/artifactIdversion1.2.16/version/dependency!-- Testing Dependencies --dependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.9/versionscopetest/scope/dependency/dependenciesbuildfinalNamedata-jpa-tutorial-part-one/finalNamepluginsplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-compiler-plugin/artifactIdversion2.3.2/versionconfigurationsource1.6/sourcetarget1.6/target/configuration/pluginplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-war-plugin/artifactIdversion2.1.1/versionconfigurationfailOnMissingWebXmlfalse/failOnMissingWebXml/configuration/pluginplugingroupIdorg.mortbay.jetty/groupIdartifactIdjetty-maven-plugin/artifactIdversion8.1.0.RC2/versionconfigurationscanIntervalSeconds0/scanIntervalSecondswebAppConfigdefaultsDescriptorsrc/main/resources/webdefault.xml/defaultsDescriptor/webAppConfig/configuration/pluginplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-site-plugin/artifactIdversion3.0/versionconfigurationreportPlugins!-- Cobertura Plugin --plugingroupIdorg.codehaus.mojo/groupIdartifactIdcobertura-maven-plugin/artifactIdversion2.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* liEnableWebMvc 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;Resourceprivate Environment environment;Beanpublic 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;}Beanpublic JpaTransactionManager transactionManager() throws ClassNotFoundException {JpaTransactionManager transactionManager new JpaTransactionManager();transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());return transactionManager;}Beanpublic 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;}Beanpublic 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;}Beanpublic 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 /;Overridepublic 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批注指定属性文件的位置该文件包含使用的配置参数的值。 我的application.properties文件的内容如下 # The default database is H2 memory database but I have also
# added configuration needed to use either MySQL and PostgreSQL.#Database Configuration
db.driverorg.h2.Driver
#db.drivercom.mysql.jdbc.Driver
#db.driverorg.postgresql.Driver
db.urljdbc:h2:mem:datajpa
#db.urljdbc:mysql://localhost:3306/datajpa
#db.urljdbc:postgresql://localhost/datajpa
db.usernamesa
db.password#Hibernate Configuration
hibernate.dialectorg.hibernate.dialect.H2Dialect
#hibernate.dialectorg.hibernate.dialect.MySQL5InnoDBDialect
#hibernate.dialectorg.hibernate.dialect.PostgreSQLDialect
hibernate.format_sqltrue
hibernate.ejb.naming_strategyorg.hibernate.cfg.ImprovedNamingStrategy
hibernate.show_sqltrue#MessageSource
message.source.basenamei18n/messages
message.source.use.code.as.default.messagetrue#EntityManager
#Declares the base package of the entity classes
entitymanager.packages.to.scannet.petrikainulainen.spring.datajpa.model配置Spring Data JPA 第三您必须配置Spring Data JPA。 如果您关注的话您可能已经注意到我在应用程序上下文配置类中使用ImportResource批注从XML配置文件中导入其他配置。 目前Spring Data JPA不支持Java配置。 因此配置它的唯一方法是使用XML配置文件。 我的pplicationContext.xml文件如下所示 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:jpahttp://www.springframework.org/schema/data/jpaxmlns:mvchttp://www.springframework.org/schema/mvcxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/data/jpahttp://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsdhttp://www.springframework.org/schema/mvchttp://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 resourcesare still served by the containers default servlet. Requires Spring Framework3.0 or higher.--mvc:default-servlet-handler/!--Configures Spring Data JPA and sets the base package of my DAOs.--jpa:repositories base-packagenet.petrikainulainen.spring.datajpa.repository/
/beans你做完了 这就对了。 我现在已经向您展示了如何配置Spring Data JPA。 我还创建了一个示例应用程序以演示此配置确实有效。 您可以通过从Github获取示例应用程序并使用Maven Jetty插件运行示例Web应用程序来自己测试配置 注意 请记住首先创建模型和存储库包。 因为无法向Git添加空目录临时区域 Github存储库也没有。 我的Spring Data JPA教程的第二部分描述了如何使用Spring Data JPA创建一个简单的CRUD Web应用程序。 敬请关注。 参考 Spring Data JPA教程第一部分来自Petri Kainulainen博客的JCG合作伙伴 Petri Kainulainen的配置 。 翻译自: https://www.javacodegeeks.com/2013/07/spring-data-jpa-tutorial-part-one-configuration.html