Bean property 'sessionFactoy' is not writable or has an invalid setter method - spring

Working on spring+hibernate+maven code.
here's my StockDaoImpl class..
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;
public class StockDaoImpl extends HibernateDaoSupport implements StockDao{
public void save(Stock stock){
getHibernateTemplate().save(stock);
}
...
My sessionfactory defined in an xml..
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibenate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>/Hibernate/Stock.hbm.xml</value>
</list>
</property>
</bean>
I get the following error in console..Bean property 'sessionFactoy' is not writable or has an invalid setter method...
I tried writing a setter function for sessionfactory in StockDaoImpl...But I get an error saying 'setSessionFactory() in HibernateDaoSupport cannot be overridden'.
Can anyone pls tell me how to resolve the issue..

Related

Spring Bean is not writable or has an invalid setter method

I'm experimenting with Spring, I'm following the book: Spring: A developer's notebook. I'm getting this error:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'validateFile' defined in class path resource [batch-config.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'customersDAO' of bean class [com.emp.ValidateCustomer]: Bean property 'customersDAO' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Below is my batch-config.xml:-
<bean id="validateFile" class="com.emp.ValidateCustomer" >
<property name="customersDAO">
<bean class="com.emp.dao.CustomerDao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</property>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="customerdb"/>
<property name="packagesToScan" value="com.emp" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="hibernate.default_batch_fetch_size">50</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">false</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
</bean>
Below is CustomersDao.java:-
#Repository
public class CustomersDao {
#SuppressWarnings("deprecation")
private HibernateTemplate hibernateTemplate=null;
#Autowired
#Qualifier("sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
}
And in ValidateCustomer.java:-
#Autowired
private CustomersDao customersDAO;
Please help.
As #MarcosBarbero says, without seeing more of ValidateCustomer.java, it's impossible to be definitive about the problem.
What annotations are on the ValidateCustomer class? I have no problem with Autowired for a private property when the enclosing class is a component or service. If it's not, then do you have a public setter? The property is not public, if the setter is not public, Spring won't be able to set it.

How to configure 'entityCacheStrategies' in spring4.3.x

I am migrating from spring3.x to spring4.3.x. I am using org.springframework.orm.hibernate5.LocalSessionFactoryBean in bean creation as follows
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>com.example.person.domain.Person</value>
</list>
</property>
<property name="mappingLocations">
<list>
<value>classpath*:com/example/person/domain/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">${cache.providerClass}</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.memcached.dogpilePrevention">true</prop>
<prop key="hibernate.memcached.servers">${cache.memcached.servers}</prop>
<prop key="hibernate.memcached.keyStrategy">com.example.memcached.ExampleCacheStringKeyStrategy</prop>
<prop key="hibernate.memcached.deviceAttributeDao.keyStrategy">com.googlecode.hibernate.memcached.HashCodeKeyStrategy</prop>
<prop key="hibernate.memcached.EncodingDao.keyStrategy">com.googlecode.hibernate.memcached.HashCodeKeyStrategy</prop>
</props>
</property>
<property name="entityCacheStrategies">
<props>
<prop key="com.example.person.domain.TestAttribute">read-write,_domain</prop>
</props>
</property>
<property name="dataSource" ref="dataSource"/>
</bean>
I am getting following error
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'entityCacheStrategies' of bean class [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Bean property 'entityCacheStrategies' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:242)
at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:423)
at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:280)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1514)
... 66 more
I am using spring-4.3.0.RELEASE. The LocalSessionFactoryBean doesn't have setter for entityCacheStrategies. Any idea how to support this in spring4.3.x?
The usage of entityCacheStrategies/setEntityCacheStrategies() has been deprecated in hibernate 5. A probable alternative from org.hibernate.cfg.Configuration : setCacheConcurrencyStrategy(String clazz, String concurrencyStrategy)is also no longer in use.
But if you're open to configuring the cache using hibernate annotations library, then try this approach which makes the use of CacheConcurrencyStrategyenumerator.
You can apply appropriate Concurrency strategy at Entity level.
#Entity
#Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Clazz{..}
Please find more usages of CacheConcurrencyStrategy in the dev guide.

Cannot get spring bean?

Can't get bean from spring container in listener or filter classes.
Have you used something like this :
#Autowired
private ApplicationContext context;
ICustomer customer = (ICustomer) context.getBean("name"); // here name is the name of the bean you want to get context
look I have used this in my project like this ans works well :
String processorName = Introspector.decapitalize(command.getClass().getSimpleName() + "Processor");
ICommandProcessor processor = (ICommandProcessor) context.getBean(processorName);
here if I ll pass command Add then it ll pass processorName = AddProcessor and get it's context.
what is your requirement ? can you post code ?
Look this xml file then check yours from it :
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="com.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
here : <property name="packagesToScan" value="com.domain"/> is important when you want to use #Autowired in my project it's com.domain, so refer this and make changes as you need. then again post.

org.hibernate.AnnotationException: No identifier specified for entity - even when it was

I have the following configuration:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="jpaDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.example.domain</value>
<value>com.example.repositories</value>
</list>
</property>
</bean>
I have my Geoname class in com.example.domain:
#Entity
#Table(name="geonames")
public class Geoname implements Serializable {
#Id
#Column(name="geonameid")
private Long geonameid = null;
}
yet, when running, I get the following exception:
Caused by: org.hibernate.AnnotationException: No identifier specified
for entity: com.example.domain.Geoname at
org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:277)
at
org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:224)
at
org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:664)
at
org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3449)
at
org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3403)
at
org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1330)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1730)
Any ideas why?
side note: I am combining both mongodb and hibernate/ mysql on this project.
I had the following
import org.springframework.data.annotation.Id;
Naturally, it should be:
import javax.persistence.Id;
Thanks to #JB Nizet
I faced the same error.I solved it and figured out i didn't put #Id annotations in id field in my Entity class.
#Entity
#Table(name="geonames")
public class Geoname implements Serializable {
#Column(name="geonameid")
private Long geonameid = null;
}
try this
#Column(name="geonameid",unique=true,nullable=false)

Spring's Java Based configuration not working for me

I am new to Spring programming and currently struggling with Spring 3.1's Java Based Configuraion" I have created following Configuration class
#Configuration
#ImportResource("classpath:/resources/jdbc.properties")
public class AppConfig {
#Autowired
Environment env;
private #Value("${jdbc.url}")
String url;
private #Value("${jdbc.username}")
String username;
private #Value("${jdbc.password}")
String password;
#Bean
public DataSource dataSource() {
System.out.println("Creating data Source.");
return new DriverManagerDataSource(url, username, password);
}
#Bean
public SessionFactory sessionFactory () throws Exception {
return new AnnotationSessionFactoryBuilder().setDataSource(dataSource()).setPackagesToScan("com.argusoft.loginmodule.domain").buildSessionFactory();
}
}
now when I try to run the project I get following error.
OUTPUT
SEVERE: Exception while loading the app :
java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException:
java.lang.IllegalArgumentException: javax.servlet.ServletException:
java.lang.NoClassDefFoundError:
org/springframework/core/env/EnvironmentCapable
stuck into it, Cant solve it..... I am following Spring Source Blog.
please also suggest some good tutorial in which Spring's latest Java based configuration is explained by easy to understand examples...
Thanks in advance,
From the perspective of the exception:
java.lang.NoClassDefFoundError: org/springframework/core/env/EnvironmentCapable
This question is equals to the question: Spring class EnvironmentCapable
So the correct answer might be:
I think that need use version 3.1.0 - in package
org.springframework.core-3.1.0.M2.jar this class presents.
given by user810430 here: original answer.
you can puth configuration like this
inside application context:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<import resource="db-config.xml" />
and
db-config.xml is:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver.className}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" autowire="byName">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="packagesToScan" value="com.huawei.sa.album" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- uncomment this for first time run-->
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven />
</beans>

Resources