I have the following configuration in my spring boot application:
#Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
#Value("${ds.fake.driverClass}") String driverClass,
#Value("${ds.fake.url}") String url,
#Value("${ds.fake.user}") String user,
#Value("${ds.fake.password}") String password,
#Value("${ds.fake.hibernateDialect}") String hibernateDialect){
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
// bean.setPersistenceUnitName("fake");
bean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
bean.setPersistenceUnitManager(persistenceUnitManager(driverClass,url,user,password));
bean.setJpaVendorAdapter(adapter());
bean.setJpaProperties((Properties)fakeJpaProperties(hibernateDialect).get());
bean.setDataSource(fakeDataSource(driverClass,url,user,password));
//bean.setPackagesToScan("my.required.package");
bean.afterPropertiesSet();
return bean;
}
#Bean
public MergingPersistenceUnitManager persistenceUnitManager(
#Value("${ds.fake.driverClass}") String driverClass,
#Value("${ds.fake.url}") String url,
#Value("${ds.fake.user}") String user,
#Value("${ds.fake.password}") String password){
MergingPersistenceUnitManager merger = new MergingPersistenceUnitManager();
// merger.setPersistenceXmlLocations("classpath*:META-INF/fake/persistence.xml");
merger.setPackagesToScan("my.required.package");
// merger.setDefaultDataSource(fakeDataSource(driverClass,url,user,password));
return merger;
}
#Bean
public HibernateJpaVendorAdapter adapter(){
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setGenerateDdl(false);
return adapter;
}
#Bean(initMethod="init",destroyMethod="close")
public static PoolingDataSource fakeDataSource(
#Value("${ds.fake.driverClass}") String driverClass,
#Value("${ds.fake.url}") String url,
#Value("${ds.fake.user}") String user,
#Value("${ds.fake.password}") String password) {
PoolingDataSource bean = new PoolingDataSource();
bean.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource");
bean.setUniqueName("fakeDataSource");
bean.setMinPoolSize(2);
bean.setMaxPoolSize(10);
bean.setMaxIdleTime(900);
bean.setUseTmJoin(true);
bean.setDeferConnectionRelease(true);
bean.setAutomaticEnlistingEnabled(true);
bean.setAllowLocalTransactions(true);
bean.setIsolationLevel("READ_COMMITTED");
Properties props = new Properties();
props.setProperty("driverClassName", driverClass);
props.setProperty("url", url);
props.setProperty("user", user);
props.setProperty("password", password);
bean.setDriverProperties(props);
return bean;
}
If i start up my application I am getting the following error:
Caused by: java.lang.IllegalStateException: Persistence unit with name 'default' already obtained
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.obtainPersistenceUnitInfo(DefaultPersistenceUnitManager.java:678)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.determinePersistenceUnitInfo(LocalContainerEntityManagerFactoryBean.java:355)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:307)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 21 more
However, If i Try to uncomment the line bean.setPersistenceUnitName("fake"); , I get the new error:
Caused by: java.lang.IllegalArgumentException: No persistence unit with name 'fake' found
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.obtainPersistenceUnitInfo(DefaultPersistenceUnitManager.java:674)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.determinePersistenceUnitInfo(LocalContainerEntityManagerFactoryBean.java:355)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:307)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at com.ixaris.providers.fake.app.boot.FakeAppBooter.entityManagerFactory(FakeAppBooter.java:226)
at com.ixaris.providers.fake.app.boot.FakeAppBooter$$EnhancerBySpringCGLIB$$6ec884df.CGLIB$entityManagerFactory$2(<generated>)
at com.ixaris.providers.fake.app.boot.FakeAppBooter$$EnhancerBySpringCGLIB$$6ec884df$$FastClassBySpringCGLIB$$cefb3e29.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at com.ixaris.providers.fake.app.boot.FakeAppBooter$$EnhancerBySpringCGLIB$$6ec884df.entityManagerFactory(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 24 more
How can I go around this / maybe "create" the persistence unit myself?
Related
I have the following quartz.properties:
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.dataSource=dataSource
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
org.quartz.jobStore.tablePrefix=qrtz_
org.quartz.threadPool.threadCount=1
org.quartz.scheduler.skipUpdateCheck=true
org.quartz.plugin.triggerHistory.class=org.quartz.plugins.history.LoggingTriggerHistoryPlugin
Also, I added QuartzConfiguration:
#Configuration
#EnableScheduling
public class QuartzConfiguration {
public static final String CONTEXT_KEY = "applicationContext";
#Autowired
private DataSource dataSource;
#Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
scheduler.setApplicationContextSchedulerContextKey("applicationContext");
scheduler.setConfigLocation(new ClassPathResource("quartz.properties"));
scheduler.setDataSource(dataSource);
scheduler.setWaitForJobsToCompleteOnShutdown(true);
return scheduler;
}
}
In the application.properties I have defined:
#PostgreSQL
spring.datasource.url=${postgresql.datasource.url}
spring.datasource.username=${postgresql.datasource.username}
spring.datasource.password=${postgresql.datasource.password}
Right now, during start up the application fails with the following exception:
Caused by: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'dataSource': java.sql.SQLException: There is no DataSource named 'dataSource' [See nested exception: java.sql.SQLException: There is no DataSource named 'dataSource']
at org.quartz.impl.jdbcjobstore.JobStoreSupport.getConnection(JobStoreSupport.java:783)
at org.quartz.impl.jdbcjobstore.JobStoreTX.getNonManagedTXConnection(JobStoreTX.java:71)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3861)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverJobs(JobStoreSupport.java:839)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:695)
... 45 more
Caused by: java.sql.SQLException: There is no DataSource named 'dataSource'
at org.quartz.utils.DBConnectionManager.getConnection(DBConnectionManager.java:104)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.getConnection(JobStoreSupport.java:780)
... 49 more
What am I doing wrong and how to provide a correct DataSource to the org.quartz.jobStore.dataSource ?
Two options:
create a configuration bean that specifically creates you DataSource.
#Bean
public DataSource getDataSource()
{
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:file:C:/temp/test");
dataSourceBuilder.username("sa");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
You can alternatively use JNDI, use the spring.datasource.jndi-name
see also
there are few answers to the question already. But none of them works for me.
I can't figure it out for the life of me why the error is coming.
Following are the approaches I tried:
using AbstractMongoConfiguration
Manually registering the mongoTemplate bean with ApplicationContext
Whenever I try to run my test during maven build or while deploying on tomcat error below comes up
Here is the configuration.
package com.fordit.project.config;
#Configuration
#EnableMongoRepositories(basePackages = "com.company.project")
#ComponentScan(basePackages = "com.company.project")
public class ProjectConfiguration {
#Value("${project.db.driver_class}")
private String driverClassname;
#Value("${project.db.connection_string}")
private String connectionString;
#Bean
public DataSource dataSource() throws PropertyVetoException {
Properties mysqlProperties = new Properties();
mysqlProperties.setProperty("characterEncoding", "UTF-8");
mysqlProperties.setProperty("useUnicode", "true");
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setProperties(mysqlProperties);
cpds.setDriverClass(driverClassname);
cpds.setJdbcUrl(connectionString);
cpds.setAcquireIncrement(2);
return cpds;
}
#Bean
public static PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() throws IOException {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();
ppc.setLocations(
resourceLoader.getResource(System.getProperty("PROJECT_CONFIGURATION_FILE")));
return ppc;
}
#Bean
public static RoleHierarchy roleHierarchy() {
String roleHierarchyStringRepresentation
= Role.ROLE_ADMIN + " > " + Role.ROLE_FIRM + "\n"
+ Role.ROLE_FIRM + " = " + Role.ROLE_LAWYER+ "= "+Role.ROLE_USER;
//logger.info("Registered Role Hierarchy: \n{}", roleHierarchyStringRepresentation);
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy(roleHierarchyStringRepresentation);
return roleHierarchy;
}
}
Mongo Configuration:
#Configuration
#ComponentScan(basePackages = "com.company.project")
#Profile("container")
public class MongoDBConfiguration extends AbstractMongoConfiguration {
#Value("${project.mongodb.hostname}")
private String host;
#Value("${project.mongodb.port}")
private Integer port;
#Value("${project.mongodb.name}")
private String db;
#Value("${project.mongodb.username}")
private String username;
#Value("${project.mongodb.password}")
private String password;
#Value("${project.mongodb.authenticationDB}")
private String authDB;
#Bean
public MongoTemplate mongoTemplate()
throws UnknownHostException, java.net.UnknownHostException {
return new MongoTemplate(
new SimpleMongoDbFactory(
mongoClient(),
getDatabaseName()
)
);
}
#Override
#Bean
public MongoClient mongoClient() {
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient(
new ServerAddress(host, port),
Collections.singletonList(
MongoCredential.createMongoCRCredential(
username,
authDB,
password.toCharArray()
)
)
);
} catch (java.net.UnknownHostException ex) {
Logger.getLogger(MongoDBConfiguration.class.getName()).log(Level.SEVERE, null, ex);
}
return mongoClient;
}
#Override
protected String getDatabaseName() {
return db;
}
}
Error log:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'forumDAL' defined in file [/home/ashay/projects/kuber/target/classes/com/fordit/kuber/forum/ForumDAL.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'forumRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:107)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:243)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 26 more
Get rid of the Profile("container") in MongoDBConfiguration.
Explanation: Because the #Profile is there, that means that that class will not be instantiated by Spring unless you are running Spring with that profile. My guess is that you are not setting spring.profiles.active property to "container" when you run your application via Tomcat or during your integration testing.
If you want to leave the #Profile("container") there then just make sure you set the profile to "container". There are multiple ways to do this. One quick easy way is to use Java system properties, e.g. -Dspring.profiles.active=container, when you execute your integration tests or run your application in Tomcat.
I have a spring application deplyoed in WebSphere container.
I trying to initialize data using liquibase.
This is my DataSource configuration:
#Bean
public JndiTemplate jndi() {
return new JndiTemplate();
}
#Bean
public PlatformTransactionManager transactionManager() {
return new WebSphereUowTransactionManager();
}
#Bean(name = "primary")
public AbstractEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setPersistenceUnitName(PERSTESTENCE_UNIT_NAME);
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setDatabase(Database.H2);
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
return entityManagerFactory;
}
#Bean
public DataSource dataSource() throws NamingException {
return jndi().lookup(DATA_SOURCE_ADDRESS, DataSource.class);
}
And this is the code that runs database initialisation:
#Startup
#Singleton
#Interceptors(SpringBeanAutowiringInterceptor.class)
public class Startup {
#Autowired
private DbInit dbInit;
#PostConstruct
public void initialize() {
try {
dbInit.doMigrations(null);
} catch (SQLException | LiquibaseException e) {
LOG.error(e);
}
}
I get an exception on application startup:
Caused by: liquibase.exception.DatabaseException: liquibase.exception.DatabaseException: java.sql.SQLException: DSRA9350E: Operation Connection.rollback is not allowed during a global transaction.
at liquibase.database.AbstractJdbcDatabase.rollback(AbstractJdbcDatabase.java:1143)
at liquibase.lockservice.StandardLockService.acquireLock(StandardLockService.java:197)
... 142 more
Caused by: liquibase.exception.DatabaseException: java.sql.SQLException: DSRA9350E: Operation Connection.rollback is not allowed during a global transaction.
at liquibase.database.jvm.JdbcConnection.rollback(JdbcConnection.java:340)
at liquibase.database.AbstractJdbcDatabase.rollback(AbstractJdbcDatabase.java:1141)
... 143 more
Caused by: java.sql.SQLException: DSRA9350E: Operation Connection.rollback is not allowed during a global transactionи.
at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.rollback(WSJdbcConnection.java:3372)
at liquibase.database.jvm.JdbcConnection.rollback(JdbcConnection.java:337)
... 144 more
I know that I can't use rollback() in container-managed transaction but I don't know, how to configure this for liquibase.
I've tried to set Non-transactional data source property in WS DataSource configuration but it didn't help.
How can I solve this problem?
Error Logs:
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.372 sec <<< FAILURE!
testCRUDCategory(net.kzn.shoppingbackend.test.CategoryTestCase) Time elapsed: 0.124 sec <<< ERROR!
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy32.add(Unknown Source)
HibernateConfig.java
#Configuration
#ComponentScan(basePackages={"net.kzn.shoppingbackend.dto"})
#EnableTransactionManagement
public class HibernateConfig {
// Change the below based on the DBMS you choose
private final static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/onlineshopping";
private final static String DATABASE_DRIVER = "org.h2.Driver";
private final static String DATABASE_DIALECT = "org.hibernate.dialect.H2Dialect";
private final static String DATABASE_USERNAME = "sa";
private final static String DATABASE_PASSWORD = "";
// dataSource bean will be available
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
// Providing the database connection information
dataSource.setDriverClassName(DATABASE_DRIVER);
dataSource.setUrl(DATABASE_URL);
dataSource.setUsername(DATABASE_USERNAME);
dataSource.setPassword(DATABASE_PASSWORD);
return dataSource;
}
// sessionFactory bean will be available
#Bean
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("net.kzn.shoppingbackend.dto");
return builder.buildSessionFactory();
}
// All the hibernate properties will be returned in this method
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", DATABASE_DIALECT);
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
// transactionManager bean
#Bean
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
Test Class
CategoryTestCase.java
public class CategoryTestCase {
private static AnnotationConfigApplicationContext context;
private static CategoryDAO categoryDAO;
private Category category;
#BeforeClass
public static void init() {
context = new AnnotationConfigApplicationContext();
context.scan("net.kzn.shoppingbackend");
context.refresh();
categoryDAO = (CategoryDAO)context.getBean("categoryDAO");
}
#Test
public void testAddCategory() {
category = new Category();
category.setName("Laptop");
category.setDescription("This is some description for laptop!");
category.setImageURL("CAT_105.png");
assertEquals("Successfully added a category inside the table!",true,categoryDAO.add(category));
}
}
why I am getting Could not open Hibernate Session for transaction; nested exception , it seems everything is fine to why this error i am getting
YOu can check git Hub code too its same issue kindly help me to solve the issue
https://github.com/rustyamigo/online-shopping
I have cloned your project and found Connection is broken: "java.net.ConnectException: Connection refused: localhost" [90067-194]),You seem not to have started the H2 server. Based on your URL, you're using tcp connection, ie the server has to be started first.
I have some googling and found you can solve it by 2 ways:
you need a java master program which start the server like this:
org.h2.tools.Server.createTcpServer().start();
e.g:
in your test class-> ProductTestCase.java
#BeforeClass
public static void init() throws Exception {
org.h2.tools.Server.createTcpServer().start();
context = new AnnotationConfigApplicationContext();
context.scan("net.kzn.shoppingbackend");
context.refresh();
productDAO = (ProductDAO)context.getBean("productDAO");
}
or you could start it manually prior to your connection attempt like this:
java -cp h2*.jar org.h2.tools.Server
My application doesnt use persistence.xml. So I tried using LocalContainerEntityManagerFactoryBean to create a custom EntityManager. But I get error as DataSource must not be null. Can anyone help on this issue?
PersistenceJPAConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories
public class PersistenceJPAConfig {
#Autowired
private DataSource dataSource;
#Autowired
JpaVendorAdapter jpaVendorAdapter;
#Bean(name = "personEntityManager")
public EntityManager entityManager() {
return entityManagerFactory().createEntityManager();
}
#Bean(name = "personEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setPackagesToScan("com.myc.cc.domain.Person");
lef.setPersistenceUnitName("personPersistenceUnit");
lef.afterPropertiesSet();
return lef.getObject();
}
#Primary
#Bean(name = "personTransactionManager")
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
}
SearchPersonPredicates.java
public static Predicate findIdByEM(final Long pId) {
PersistenceJPAConfig jpaConfig = new PersistenceJPAConfig();
EntityManager manager= jpaConfig.entityManager();
QPerson qPerson = QPerson.person;
QAddress qAddress = QAddress.address;
BooleanBuilder booleanBuilder = new BooleanBuilder();
JPAQuery jpaQuery = new JPAQuery(manager);
JPASubQuery subQuery = new JPASubQuery();
Predicate predicate;
if (pId != null) {
booleanBuilder.or(QAddress.person_no.eq(pId));
}
predicate = booleanBuilder.getValue();
jpaQuery = jpaQuery.from(qAddress).join(qPerson).on(predicate);
subQuery.from(qPerson, qAddress);
return predicate;
}
SearchPersonServiceImpl.java
public List<Person> findPnumberbyEM(Long id) {
Iterable<Person> person = personRepository.findAll(findIdByEM(id));
return constructList(person);
}
private List<Person> constructList(Iterable<Person> persons) {
List<Person> list = new ArrayList<Person>();
for (Person person : persons) {
list.add(person);
}
}
Error
17:52:35.337 ERROR 7016 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/cc_dev] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: DataSource must not be null] with root cause
java.lang.IllegalArgumentException: DataSource must not be null
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.jdbc.datasource.lookup.SingleDataSourceLookup.<init>(SingleDataSourceLookup.java:40)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.setDataSource(LocalContainerEntityManagerFactoryBean.java:238)
at com.myc.cc.repository.PersistenceJPAConfig.entityManagerFactory(PersistenceJPAConfig.java:43)
at com.myc.cc.repository.PersistenceJPAConfig.entityManager(PersistenceJPAConfig.java:37)
at com.myc.cc.repository.SearchPersonPredicates.findIdByEM(SearchPersonPredicates.java:121)
at com.myc.cc.service.impl.SearchPersonServiceImpl.findPnumberbyEM(SearchPersonServiceImpl.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:201)
at com.sun.proxy.$Proxy114.findPnumberbyEM(Unknown Source)
at com.myc.cc.web.SearchPersonController.searchPerson(SearchPersonController.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
Thanks in advance
Your datasource property may not be getting initialized. Try adding #Value to datasource property:
#Autowired
#Value("${property.reference}")
private DataSource dataSource;