2
我對spring比較新,想用mysql實現spring jpa。下面提到的是我的配置...通過配置類創建transactionmanager和實體管理器
<beans ...
<context:component-scan base-package="com.pg" />
<mvc:annotation-driven />
<tx:annotation-driven/>
<aop:aspectj-autoproxy />
<jpa:repositories base-package="com.pg.dao" /> ...
我的配置類創建數據源,transactionmanager和entitymanager下面列出。
package com.pg.conf;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
@Configuration
public class JPAConfiguration {
@Bean
public DataSource dataSource(){
BasicDataSource datasource = new BasicDataSource();
datasource.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
datasource.setUrl("jdbc:mydql://localhost:3306/pg1");
datasource.setUsername("root");
datasource.setPassword("root");
return datasource;
}
@Bean
public **FactoryBean<EntityManagerFactory>** entityManagerFactory(){
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setDataSource(dataSource());
HibernateJpaVendorAdapter adaptor = new HibernateJpaVendorAdapter();
containerEntityManagerFactoryBean.setJpaVendorAdapter(adaptor);
containerEntityManagerFactoryBean.setPackagesToScan("com.pg.entity");
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
props.setProperty("hibernate.show_sql", "true");
containerEntityManagerFactoryBean.setJpaProperties(props);
return containerEntityManagerFactoryBean;
}
@Bean
public TransactionManager transactionManager(){
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(dataSource());
**jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());**
return transactionManager();
}
}
我有上線jpaTransactionManager.setEntityManagerFactory誤差(的entityManagerFactory());
我認爲EntityManager的方法的返回類型是不正確的......即使它沒有顯示錯誤....
任何幫助表示讚賞。
實際上'FactoryBean' + JavaConfig存在代理問題,不建議直接使用'getObject()',特別是在bean配置階段。作爲一個技巧:使用'FactoryBean'的結果作爲bean-method參數,autowire處理器爲你做這些事情。 –
謝謝。這有助於。我在spring beans xml文件中創建了事務管理器,目前事情正在正常工作。 – user2775185
這是你在那裏得到的一些無意義的代碼。 –