我正在尝试集成eclipselink JPA到我的Spring Web应用程序中。 有什么好的指南哦,如何仅使用基于Java的配置在Spring MVC中为MySql数据库配置eclipseLink? 。没有dispatcher-servlet.xml。
eclipselink JPA
我熟悉基于Java的Spring配置。(使用@Configuration, @EnableWebMvc, @ComponentScan, @EnableTransactionManagement等)。但是不熟悉Spring MVC中基于eclipseLink java的配置。
@Configuration, @EnableWebMvc, @ComponentScan, @EnableTransactionManagement
以下是 pom.xml
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>roster3</groupId> <artifactId>roster3</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>roster3 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.0.2.RELEASE</spring.version> <hibernate.version>4.3.4.Final</hibernate.version> <hibernate.validator.version>5.1.0.Final</hibernate.validator.version> <mysql.connector.version>5.1.29</mysql.connector.version> <eclipselink.version>2.5.0</eclipselink.version> <aspectj.version>1.5.4</aspectj.version> </properties> <repositories> <repository> <id>oss.sonatype.org</id> <name>OSS Sonatype Staging</name> <url>https://oss.sonatype.org/content/groups/staging</url> </repository> </repositories> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <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>org.springframework</groupId> <artifactId>spring-tx</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> <!-- Servlet & jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Hibernate Validation & DB Validation --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate.validator.version}</version> </dependency> <!-- eclipselink --> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>${eclipselink.version}</version> <exclusions> <exclusion> <groupId>org.eclipse.persistence</groupId> <artifactId>commonj.sdo</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> </dependencies> <build> <!-- To define the plugin version in your parent POM --> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.3-SNAPSHOT</version> <configuration> <url>http://127.0.0.1:8080/roster3</url> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> <argLine>-javaagent:eclipselink.jar</argLine> </configuration> </plugin> <!-- This plugin ensures the EclipseLink static weaving --> <plugin> <artifactId>eclipselink-staticweave-maven-plugin</artifactId> <groupId>au.com.alderaan</groupId> <version>1.0.4</version> <executions> <execution> <goals> <goal>weave</goal> </goals> <phase>process-classes</phase> <configuration> <logLevel>ALL</logLevel> <!-- <includeProjectClasspath>true</includeProjectClasspath> --> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>${eclipselink.version}</version> </dependency> </dependencies> </plugin> </plugins> <pluginManagement> <plugins> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. --> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId> au.com.alderaan </groupId> <artifactId> eclipselink-staticweave-maven-plugin </artifactId> <versionRange> [1.0.4,) </versionRange> <goals> <goal>weave</goal> </goals> </pluginExecutionFilter> <action> <execute> <runOnIncremental>true</runOnIncremental> </execute> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </pluginManagement> <finalName>roster3</finalName> </build> </project>
以下是我到目前为止所做的尝试。
配置类 Config.java
Config.java
package com.ecw.roster.config; import java.util.Properties; import org.eclipse.persistence.platform.database.DatabasePlatform; import org.eclipse.persistence.platform.database.MySQLPlatform; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect; import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; @Configuration //Marks this class as configuration @EnableWebMvc //Specifies which package to scan @ComponentScan("com.ecw.roster") @PropertySource(value = "classpath:application.properties") //Enable Spring's annotations @EnableTransactionManagement public class Config extends WebMvcConfigurerAdapter{ private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect"; 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_DATABASEPLATFORM = "databasePlatform"; private static final String PROPERTY_NAME_GENERATE_DDL = "generateDdl"; private static final String PROPERTY_NAME_SHOW_SQL = "showSql"; @Value("${jdbc.driverClassName}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${hibernate.dialect}") private String hibernate_dialect; @Value("${hibernate.show_sql}") private String hibernate_show_sql; @Value("${entitymanager.packages.to.scan}") private String entity_package_to_scan; @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public UrlBasedViewResolver setupViewResolver() { UrlBasedViewResolver resolver = new UrlBasedViewResolver(); System.out.println("Roster 3 : Initializing UrlBasedViewResolver........"); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); resolver.setViewClass(JstlView.class); return resolver; } @Bean public PlatformTransactionManager transactionManager(){ System.out.println("Roster 3 : LocalContainerEntityManagerFactoryBean *************"); JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject()); return transactionManager; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setPackagesToScan(new String[] { "com.ecw.roster.beans" }); em.setPersistenceUnitName("roster3"); DatabasePlatform dp = new MySQLPlatform(); em.setJpaVendorAdapter(getEclipseLinkJpaVendorAdapter()); return em; } private EclipseLinkJpaVendorAdapter getEclipseLinkJpaVendorAdapter(){ System.out.println("Roster 3 : EclipseLinkJpaVendorAdapter initialization ***************"); EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter(); vendorAdapter.setDatabasePlatform("org.eclipse.persistence.platform.database.MySQLPlatform"); vendorAdapter.setGenerateDdl(false); vendorAdapter.setShowSql(true); return vendorAdapter; } private Properties eclipseLinkProperty(){ Properties properties = new Properties(); properties.put("eclipselink.deploy-on-startup", "true"); properties.put("eclipselink.ddl-generation", "create-or-extend-tables"); properties.put("eclipselink.ddl-generation.output-mode", "database"); properties.put("eclipselink.weaving", "static"); properties.put("eclipselink.weaving.lazy", "true"); properties.put("eclipselink.weaving.internal", "true"); properties.put("eclipselink.logging.level", "SEVERE"); properties.put("eclipselink.query-results-cache.type", "WEAK"); properties.put("eclipselink.jdbc.batch-writing", "JDBC"); properties.put("eclipselink.jdbc.batch-writing.size", "1000"); return properties; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { System.out.println("In Resouce Handler"); registry.addResourceHandler("/resources/**").addResourceLocations("/resources/defaultTheme/"); } @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("/WEB-INF/messages/messages/"); return messageSource; } }
eclipselink的persistence.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="roster3" transaction-type="RESOURCE_LOCAL"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <class>com.ecw.roster.beans.Roster</class> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/roster" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="mysqladmin" /> </properties> </persistence-unit> </persistence>
我能够构建和部署项目,但出现连接泄漏,然后我的上下文被tomcat容器停止了。
请告诉我我在做什么错。
谢谢
以下配置将使Spring能够使用两个应用程序上下文(根上下文和Web应用程序上下文),并将配置您所需的大多数内容。
@Configuration @EnableTransactionManagement @EnableMBeanExport @EnableJpaRepositories("your.jpa.repositories.package") @ComponentScan(basePackages = "gr.xe.payments", excludeFilters = {@ComponentScan.Filter(value = Controller.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE ,value = MvcConfig.class)}) public class ApplicationConfig { } @EnableWebMvc @ComponentScan(basePackages = "your.controller.package", includeFilters = @ComponentScan.Filter(value = Controller.class)) public class MvcConfig extends WebMvcConfigurerAdapter { @Bean public TilesConfigurer tilesViewResolver() { TilesConfigurer tilesViewResolver = new TilesConfigurer(); tilesViewResolver.setDefinitions(new String[]{"/WEB-INF/tiles.xml"}); return tilesViewResolver; } @Bean public UrlBasedViewResolver urlBasedViewResolver() { UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver(); urlBasedViewResolver.setViewClass(TilesView.class); return urlBasedViewResolver; } @Bean(name = "messageSource") public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource() { ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource(); reloadableResourceBundleMessageSource.setBasename("WEB-INF/i18n/messages"); reloadableResourceBundleMessageSource.setFallbackToSystemLocale(false); reloadableResourceBundleMessageSource.setDefaultEncoding("UTF-8"); return reloadableResourceBundleMessageSource; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } } @Configuration public class DatabaseConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter(); vendorAdapter.setGenerateDdl(true); vendorAdapter.setShowSql(false); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("your.domain.package"); factory.setDataSource(dataSource()); factory.setJpaProperties(jpaProperties()); return factory; } @Bean public JpaTransactionManager transactionManager() { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory().getObject()); return txManager; } @Bean public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() { return new PersistenceExceptionTranslationPostProcessor(); } @Bean public DataSource dataSource() { //This uses JNDI, you could create the data source in any way you want try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); return (DataSource) envCtx.lookup("jdbc/yourDS"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Unable to lookup datasource", e); } } private Properties jpaProperties() { Properties properties = new Properties(); //use whatever EclipseLink properties you like return properties; } }
编辑:
相关的依赖关系是
<properties> <spring.version>3.2.8.RELEASE</spring.version> <spring-security.version>3.1.3.RELEASE</spring-security.version> </properties> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <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>org.springframework</groupId> <artifactId>spring-context-support</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-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.2.0.RELEASE</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> <exclusion> <artifactId>jcl-over-slf4j</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>2.5.1</version> </dependency>