i am relatively new to spring and want to implement the spring jpa with mysql. below mentioned is my configurations...
<beans ...
<context:component-scan base-package="com.pg" />
<mvc:annotation-driven />
<tx:annotation-driven/>
<aop:aspectj-autoproxy />
<jpa:repositories base-package="com.pg.dao" /> ...
My configuation class to create the datasource, transactionmanager and entitymanager is listed below.
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();
}
}
i have error on the line jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
i think the returntype of the entitymanager method is not correct... even though it does not show error....
Any help is appreciated.
Start with reading the Spring reference guide and read about FactoryBeans.
Then change your code accordingly.
#Bean
public TransactionManager transactionManager(EntityManagerFactory entityManagerFactory){
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(dataSource());
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
return jpaTransactionManager;
}
Replace
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
with
jpaTransactionManager.setEntityManagerFactory((EntityManagerFactory) entityManagerFactory());
Related
As a developer
I would like to develop a Spring JPA to access Oracle 9i database to fetch records via stored procedures
I want to connect to the database via application.yml but I initiate the project with the configuration file application.properties
I declare this in application.properties
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.dialect=org.hibernate.dialect.Oracle9iDialect
spring.jpa.database=default
spring.main.allow-bean-definition-overriding=true
spring.datasource.driverClassName=oracle.jdbc.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle9iDialect
and in application.yml
jpa:
hibernate:
ddl-auto: none
naming:
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
properties:
hibernate:
proc.param_null_passing: true
dialect: org.hibernate.dialect.Oracle9iDialect
show-sql: true
When it comes to execution, it raises the following exceptions
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Would you please tell me what other ways for me to modify the class or configuration file?
Here is my code of Configuration Class :
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class})
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "productEntityManagerFactory",
transactionManagerRef = "productTransactionManager",
basePackages = {"com.pccw.ruby.repository"})
public class DBConfiguration {
#Primary
#Bean
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setPackagesToScan("com.pccw.ruby.domain");
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.proc.param_null_passing", new Boolean(true));
jpaProperties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
jpaProperties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
factoryBean.setJpaProperties(jpaProperties);
return factoryBean;
}
#Primary
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
Here is my oracle database version :
Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.proc.param_null_passing", new Boolean(true));
jpaProperties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
jpaProperties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle9iDialect");
Try setting it here.
I have Spring based application and I need to get Hibernate working. So I got inspired by this tutorial: A Guide to Hibernate with Spring 4 and I created java class(I want to configure Hibernate xml-less):
package com.mycompany.cmms.web.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class PersistanceJPAConfig {
#Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.vsb.cmms.domain" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em.getObject();
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/cmms");
dataSource.setUsername( "postgres" );
dataSource.setPassword( "xxx" );
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.setProperty("hibernate.query.factory_class", "org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory");
return properties;
}
}
But when I build and start my application i get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in com.vsb.cmms.web.config.PersistanceJPAConfig: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'entityManagerFactory' or 'persistenceUnitName' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: 'entityManagerFactory' or 'persistenceUnitName' is required
at org.springframework.orm.jpa.JpaTransactionManager.afterPropertiesSet(JpaTransactionManager.java:304)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
... 21 more
The error is saying that'entityManagerFactory' or 'persistenceUnitName' is required. But entity manager factory should be provided via entityManagerFactory().
When I debbuged thi bean I noticed that em.getObject() is returning null and possibly is causing the error although I do not know why is this happening. I am using Spring 4 and Hibernate 5.2.3.Final.
Your entityManagerFactory() method really shouldn't be calling #getObject() but instead you should write it as:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.vsb.cmms.domain" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
// just return the bean here
return em;
}
Spring handles that factory bean automatically giving your EntityManagerFactory instances.
Just found in the deeps of the internet...
If you want to make xml-less hibernate configuration with a chance easily control session(session for application or session for transaction), then you probably want to see this
Please note, the code as it is works perfectly until Hibernate 5.2 version
I have created ear project with one web module and one EJB module.
I'm using web module for Spring MVC view and controller. Model, service and repository are maintained in ejb module. (tried in JAR module as well).
I'm getting exception like, [springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 168) Context initialization failed: java.lang.IllegalStateException: Cannot load configuration class: com.sakthi.core.config.HibernateConfiguration Exception.
My HibernateConfiguration class is,
package com.sakthi.core.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class HibernateConfiguration {
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.sakthi.core.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
My Complete project is copied in github URL: https://github.com/newway86/Spring4MVCHibernateEAR/tree/master/myapp
Please help me... I'm trying for 2 months. Not yet getting the sollution.
This actual program has been taken from this URL: http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/
If I try the above example in web project, its working fine. But not working while I create it as a ear project and moved the core logics to the ejb module.
I have some problem when inherit session factory and configuration from another project :
I have two separate project (core-project, the projects uses core as library)
configuration of my core-project is the following code :
package ir.badnava.pressmining.core.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import ir.badnava.pressmining.core.models.raw.base.BaseRawEntity;
import ir.badnava.pressmining.core.models.raw.page.RawPageEntity;
#Configuration
#ComponentScan(basePackages = { "ir.badnava.pressmining" })
#EnableTransactionManagement
#PropertySource(value = { "classpath:database.properties" })
public class AppConfig {
#Autowired
private Environment environment;
#Bean(name = "sessionFactory")
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(getDataSource());
setAnotatedClasses(sessionFactory);
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
protected void setAnotatedClasses(LocalSessionFactoryBean sessionFactory) {
sessionFactory.setAnnotatedClasses(new Class<?>[]{BaseRawEntity.class, RawPageEntity.class});
}
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager(s);
return txManager;
}
}
and the child project configuration is the following code :
package com.badnava.pressmining.web.crawler.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import com.badnava.pressmining.web.crawler.crawler.WebCrawler;
import com.badnava.pressmining.web.crawler.models.speciallist.RepositoryList;
import com.badnava.pressmining.web.crawler.models.speciallist.RepositoryListManager;
import com.badnava.pressmining.web.crawler.models.urlrepo.UrlRepository;
import com.badnava.pressmining.web.crawler.models.urlrepo.UrlRepositoryManager;
#Configuration
public class AppConfig extends ir.badnava.pressmining.core.config.AppConfig{
#Bean
public RepositoryListManager getRepositoryListManager() {
return new RepositoryListManager();
}
#Bean
public UrlRepositoryManager getUrlRepositoryManager() {
return new UrlRepositoryManager();
}
#Bean
public WebCrawler getWebCrawler(){
return new WebCrawler();
}
#Override
protected void setAnotatedClasses(LocalSessionFactoryBean sessionFactory) {
super.setAnotatedClasses(sessionFactory);
sessionFactory.setAnnotatedClasses(new Class<?>[]{RepositoryList.class, UrlRepository.class});
}
}
and my problem is that in the child project I overload the setAnnotatedClass method and calling it's super and give the session factory my entities class but after doing something like save or update session factory says that unknown mapping entity
I have no idea about what did I wrong in these code because I did that before with XML file configuration
Update :
log :
Exception in thread "Thread-3" org.hibernate.MappingException: Unknown entity: ir.badnava.pressmining.core.models.raw.page.RawPageEntity
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at ir.badnava.pressmining.core.models.raw.base.BaseDao.save(BaseDao.java:16)
at ir.badnava.pressmining.core.models.raw.base.BaseDao$$FastClassBySpringCGLIB$$d95ff2ca.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
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.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at ir.badnava.pressmining.core.models.raw.base.BaseDao$$EnhancerBySpringCGLIB$$95dae3fd.save(<generated>)
at ir.badnava.pressmining.core.models.raw.base.BaseManager.save(BaseManager.java:23)
at com.badnava.pressmining.web.crawler.crawler.WebCrawler$3.run(WebCrawler.java:142)
at java.lang.Thread.run(Thread.java:745)
Problem solved :
the problem was that the setAnnotatedClasses method is a setter method and I changed my code to bellow code and that's work
#Override
protected Class<?>[] setAnotatedClasses() {
Class<?>[] superClasses = super.setAnotatedClasses(sessionFactory);
Class<?>[] childClasses = new Class<?>[]{RepositoryList.class, UrlRepository.class};
Class<?>[] allClasses = new Class<?>[childClasses.length + superClasses.length];
for (int i = 0; i < allClasses.length; i++) {
if (i < superClasses.length)
allClasses[i] = superClasses[i];
else
allClasses[i] = childClasses[i-childClasses.length];
}
return allClasses;
}
thanks to #sura2k
Hey everyone am using spring MVC And I want ot integrate JPA Repository with JNDI Data Source , i have an app without jpa repository here's my code :
mvcConfiguration class to create my Datasource :
package net.codejava.spring.config;
import javax.naming.NamingException;
import javax.sql.DataSource;
import net.codejava.spring.dao.UserDAO;
import net.codejava.spring.dao.UserDAOImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jndi.JndiTemplate;
import org.springframework.web.servlet.ViewResolver;
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.InternalResourceViewResolver;
#Configuration
#ComponentScan(basePackages="net.codejava.spring")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public UserDAO getUserDao() throws NamingException {
JndiTemplate jndiTemplate = new JndiTemplate();
DataSource dataSource = (DataSource) jndiTemplate.lookup("java:comp/env/jdbc/postgres2");
return new UserDAOImpl(dataSource);
}
}
this Dao layer that i want to replace with Jpa repository
package net.codejava.spring.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import net.codejava.spring.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class UserDAOImpl implements UserDAO {
private DataSource dataSource;
public UserDAOImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<User> list() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "SELECT * from users";
List<User> listUser = jdbcTemplate.query(sql, new RowMapper<User>() {
#Override
public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setEmail(rs.getString("email"));
return user;
}
});
return listUser;
}
}
and the context.xml
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/postgres2" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://127.0.0.1:5432/mydb"
username="postgres" password="root" maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>
Thanks for any guide ..