i use hibernate 5 and spring 4 mapped my class and used entity name in creating queries but i get
> SEVERE: Servlet.service() for servlet [dispatcher] in context with
> path [/emusicstore] threw exception [Request processing failed; nested
> exception is java.lang.IllegalArgumentException:
> org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not
> mapped [FROM Product]] with root cause
> org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not
> mapped
part of my codes that is necessary is included!
my controller
#Controller
public class HomeController {
#Autowired
private ProductDaoImpl productDaoImpl;
#RequestMapping(value = "/productList")
public String getProduct(Model model) {
List<Product> products = productDaoImpl.getAllProducts();
model.addAttribute("products", products);
return "productList";
}
My Product getting Function
public List<Product> getAllProducts() {
Session session;
try {
session = sessionFactory.getCurrentSession();
System.out.println("SDSDSASDASDASD");
} catch (HibernateException e) {
session = sessionFactory.openSession();
System.out.println("Error in session get all");
}
Query query = session.createQuery("FROM Product");
List<Product> products = query.list();
session.flush();
return products;
}
My applicattion Context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:orcl" />
<property name="username" value="c##alireza" />
<property name="password" value="myjava123" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.mywebsite.contorller</value>
<value>com.mywebsite.dao.impl</value>
<value>com.mywebsite.model</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
tnx For ur help!
In order for Hibernate to recognize your entity class, the class must be annotated with #Entity and located in one of the packages defined in the property packagesToScan of your sessionFactory.
Related
I am having an issue when we migrated from Hibernate 4 to 5.
I have been struggling from a week and read numerous blogs and pages, but could not resolve.
Following are more information on the issue:-
1) Hibernate Version :
From: 4.3.11.Final
To : 5.4.28.Final
2) Spring ORM version : 4.3.29.RELEASE
3) Spring Batch Infrastructre/Core: 3.0.10.Release
4) Hibernate XML Configuration :
<?xml version="1.0" encoding="UTF-8"?>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/> <!-- set in another xml using org.apache.commons.dbcp.BasicDataSource -->
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.id.new_generator_mappings">true</prop>
<!-- -->
<prop key="hibernate.jdbc.batch_size">1000</prop>
<prop key="hibernate.jdbc.fetch_size">1000</prop>
<prop key="hibernate.order_inserts">true</prop>
<prop key="hibernate.order_updates">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.company.ParentTable</value>
<value>com.company.ChildTable</value>
</list>
</property>
</bean>
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate"
p:isolationLevelName="ISOLATION_READ_COMMITTED"
p:propagationBehaviorName="PROPAGATION_REQUIRES_NEW"
p:transactionManager-ref="transactionManager"
/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Spring transaction management -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"
/>
5) Spring Batch Configuration
<?xml version="1.0" encoding="UTF-8"?>
<batch:job id="loaderJob" job-repository="jobRepository">
<batch:step id="initLoader" next="pipeline">
<batch:tasklet transaction-manager="transactionManager">
<bean class="com.company.InitialLoaderTask" scope="step">
<constructor-arg name="dao" ref="dao"/>
<constructor-arg name="filter" value="#{jobParameters['filter']}"/>
</bean>
</batch:tasklet>
</batch:step>
<batch:step id="pipeline">
<batch:tasklet transaction-manager="transactionManager" task-executor="loader_multi_thread_taskExecutor" throttle-limit="50">
<batch:chunk
reader="reader"
writer="processorAndWriter"
commit-interval="1000">
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="reader" class="com.company.SynchronizedItemStreamReader" scope="step" > <!-- Custom Synchrnized Item Reader -->
<constructor-arg name="delegate" ref="#{ jobExecutionContext['region'] ? 'hibernateReader':'hibernateReader2' }"/> <!-- hibernateReader2 is same as hibernateReader but with more params -->
</bean>
<bean id="hibernateReader"
class="org.springframework.batch.item.database.HibernateCursorItemReader"
scope="step" >
<property name="sessionFactory" ref="sessionFactory"/>
<property name="queryName" value="ParentTable.query1"/>
<property name="useStatelessSession" value="false"/>
<property name="saveState" value="false"/>
<property name="fetchSize" value="10000"/>
<property name="parameterValues">
<map>
<entry key="param1" value="#{jobExecutionContext['param1']}"/>
<entry key="param2" value="#{jobExecutionContext['param2']}"/>
</map>
</property>
</bean>
<bean id="processorAndWriter"
class="com.company.LoaderAndWriter"
>
<constructor-arg name="generator" ref="processor"/>
<constructor-arg name="writer" ref="hibernateWriter"/>
</bean>
<bean id="processor" class="org.springframework.batch.item.support.CompositeItemProcessor" >
<property name="delegates">
<list>
<bean class="com.company.Generator" scope="step">
<constructor-arg name="param1" value="#{jobExecutionContext['param1']}"/>
</bean>
<bean class="com.company.Processor" scope="step">
<constructor-arg name="param3" value="#{jobExecutionContext['param3']}"/>
</bean>
</list>
</property>
</bean>
<bean id="hibernateWriter" class="org.springframework.batch.item.database.HibernateItemWriter">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="loader_multi_thread_taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="25"/>
<property name="maxPoolSize" value="50"/>
</bean>
6) Entity Objects
#Entity
#Table(name = "PARENT_TABLE")
#NamedNativeQueries({
#NamedNativeQuery(
name = "ParentTable.query1",
query = "SELECT * FROM PARENT_TABLE where param = :param1",
resultClass = ParentTable.class
)
})
#BatchSize(size = 1000)
public class ParentTable extends PersistentEntity<Long> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PARENT_TABLE_SEQ")
#SequenceGenerator(name = "PARENT_TABLE_SEQ", sequenceName = "PARENT_TABLE_SEQ", allocationSize=5)
private Long id;
#Column
private Long field1;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "fieldId", fetch = FetchType.EAGER)
#BatchSize(size = 1000)
private List<ChildTable> childTable;
}
#Entity
#Table(name = "CHILD_TABLE")
#BatchSize(size = 1000)
public class ChildTable extends PersistentEntity<Long> {
private static final long serialVersionUID = 1L;
#Id
private Long id;
#ManyToOne
#JoinColumn(name = "field1")
private ParentTable parentData;
#Column
private String field2;
}
7) Generator Class where error is thrown when access Childtable data from ParentData List
public class Generator implements ItemProcessor<List<? extends ParentTable>, RequestPojoBean> {
private final int param1;
public Generator(int param1) {
this.param1 = param1;
}
#Override
public RequestPojoBean process(List<? extends ParentTable> parentDataList) throws Exception {
RequestPojoBean result = new RequestPojoBean();
result.setParentDataList(convertToRequestList(parentDataList));
result.setparam1(param1);
return result;
}
private List<ParentRequestPojoBean> convertToRequestList(List<? extends ParentTable> parentDataList) {
List<ParentRequestPojoBean> parentRequestBean = new ArrayList<>();
for (ParentTable parentData : parentDataList) {
LOGGER.info("Parent detail " + parentData.getField1());
ParentRequestPojoBean bean1 = new ParentRequestPojoBean();
bean1.setSomeData(callToSomeServiceViaHibernate(parentData.somedata, param1));
// attach References if any
List<RequestPojoBeanChildData> childList = new ArrayList<>();
for (ChildTable child : parentData.getChildTable()) { *****<--- Exception is thrown at this line*****
RequestPojoBeanChildData childPojoData = new RequestPojoBeanChildData();
childPojoData.setField2(child.getField2());
childList.add(childPojoData);
}
bean1.setChildData(childList);
parentRequestBean.add(bean1);
}
return parentRequestBean;
}
}
8) Exception Stack Trace :
2021-04-12 13:33:42,548 ERROR [main] [org.springframework.batch.core.step.AbstractStep] - <Encountered an error executing step pipeline in job loaderJob>
java.util.ConcurrentModificationException
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:719)
at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:752)
at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:750)
at org.hibernate.engine.spi.BatchFetchQueue.getCollectionBatch(BatchFetchQueue.java:311)
at org.hibernate.loader.collection.plan.LegacyBatchingCollectionInitializerBuilder$LegacyBatchingCollectionInitializer.initialize(LegacyBatchingCollectionInitializerBuilder.java:79)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:710)
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:93)
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2163)
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:589)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:387)
As part of migration, I have updated
Hibernate version
Hibernate5.LocalSessionFactoryBean
Hibernate5.HibernateTransactionManager
If I revert back above mentioned changes for Hibernate4, the code works fine in Multi-Threaded Pool, but throws ConcurrentModificationException with above updates.
I am sure I must be missing something very silly OR some setting which needs to be added as part of Hibernate 5 migration.
Any suggestion is greatly appreciated.
Thanks in advance.
An Hibernate Session and the objects loaded from that session, altogether, are not thread safe. So you cannot load objects from a session and then use these objects in different threads.
Among other problems these objects might trigger the initialization of lazy collection/proxies, which ultimately falls on the underlying JDBC connection and that connection is not thread safe either.
You need to give each thread it's own session and you must not share objects loaded from sessions between threads
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
<prop key="org.hibernate.cache.ehcache.configurationResourceName">classpath:hibernate-ehcache.xml</prop>
<prop key="cache.provider_class">${cache.provider_class}</prop>
<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<!-- Hibernate template for hibernateSessionFactory -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Transaction Manager for hibernateSessionFactory -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="DataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Above is the Hibernate config for the spring boot application. We have addition added the following c3po config. But still the connection pool is getting maxed out.
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"></property name>
<property name="jdbcUrl" value="${ondot.jdbc.url}"></property name>
<property name="user" value="${jdbc.user}"></property name>
<property name="password" value="${jdbc.password}"></property name>
<property name="initialPoolSize" value="${initialPoolSize}" /></property name>
<property name="minPoolSize" value="${minPoolSize}"></property name>
<property name="maxPoolSize" value="${maxPoolSize}"></property name>
<property name="acquireIncrement" value="${acquireIncrement}"></property name>
<property name="maxStatements" value="${maxStatements}"></property name>
<property name="acquireRetryAttempts" value="${acquireRetryAttempts}"></property name>
<property name="acquireRetryDelay" value="${acquireRetryDelay}"> </property name>
<property name="breakAfterAcquireFailure"
value="${breakAfterAcquireFailure}"></property name>
<property name="maxIdleTime" value="${maxIdleTime}"> </property name>
and following is the property file:
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.generate_statistics=true
cache.provider_class=org.hibernate.cache.EhCacheProvider
initialPoolSize=5
minPoolSize=100
maxPoolSize=250
acquireIncrement=5
maxStatements=100
acquireRetryAttempts=10
acquireRetryDelay=1000
breakAfterAcquireFailure=false
maxIdleTime=1800
The session factory is autowired and a simple code with Open and close session is written.
public class BasicAunthenticationImpl {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void setSessionFactory(SessionFactory sessionFactory)
{
BasicAunthenticationImpl.sessionFactory = sessionFactory;
}
}
public class Module1
{
#Autowired
private SessionFactory sessionFactory;
private Session session = null;
#Override
public void process(List<RoutableModuleData> routableProcessObjects)
throws OndotException
{
try
{
session = sessionFactory.openSession();
session.flush();
canonicalMessage =
lookupprocesser.processInput(canonicalMessage,
Constants.L1_LOOKUP_CACHE, session);
}
catch (Exception Ex)
{
}
finally
{
if (session != null && session.isOpen()){
session.close();
}
}
}
}
public class Lookupprocesser{
public CanonicalMessage processInput(CanonicalMessage canonicalMessage,
String cacheLookup, Session session) throws DataInsightsCommonException
{
lookupSearchForL1(canonicalMessage, session, cacheLookup);
return canonicalMessage;
}
}
public class Query{
public List<TerminalData> searchByMatchKey1AndMatchKey2(Session
session, String matchKey1, String matchKey2) throws
DataInsightsCommonException
{
Query query;
List<Data> t = null;
query = session.createQuery("from Data as odt where odt.Key1 is
null and odt.Key2 = :Key2");
query.setParameter(Constants.KEY2, Key2);
query.setCacheable(true);
terminals = (List<Data>) query.list();
return (null != t && !t.isEmpty()) ? t : null;
}
}
The Session object is shared among all classes and object, I edited the code below , BasicAuth class creates the SessionFactory
The Module1 will call LookupProcessor and which will call the query class. We are closing the session on the Module1.
here is my 'GenericQuartzJob' class
public class GenericQuartzJob extends QuartzJobBean
{
private String batchProcessorName;
public String getBatchProcessorName() {
return batchProcessorName;
}
public void setBatchProcessorName(String name) {
// System.out.println("jo"+name);
this.batchProcessorName = name;
}
protected void executeInternal(JobExecutionContext jobCtx) throws JobExecutionException
{
try {
// System.out.println("jo");
SchedulerContext schedCtx = jobCtx.getScheduler().getContext();
ApplicationContext appCtx =
(ApplicationContext) schedCtx.get("applicationContext");
java.lang.Runnable proc = (java.lang.Runnable) appCtx.getBean(batchProcessorName);
proc.run();
}
catch (Exception ex) {
// ex.printStackTrace();
throw new JobExecutionException("Unable to execute batch job: " + batchProcessorName, ex);
}
}
}
Here is my MyRunnableJob Class
#Configuration
#ComponentScan("com.ehydromet.service")
public class MyRunnableJob implements Runnable {
//#Resource private SpringService myService;
#Autowired
public UserService service;
#Override
public void run() {
// System.out.println("hu");
try{
service.getAllAdminUser();
}catch(Exception ex){
System.out.println(ex.getMessage()+" MyRunnableJob");
}MqttImplement mqtt=new MqttImplement();
mqtt.publishMessage();
//Run the Job. This code will run in the Spring context so you can use injected dependencies here.
}
}
Below is my MqttImplement class
public class MqttImplement implements MqttCallback {
#Autowired
private static UserService service;
#RequestMapping("/publish")
public void publishData(ModelMap map){
MyTask.map=map;
pubTopic="tmsdata";
susTopic="tmsack";
if(initializeMqTTParameters() ){
if(suscribeForAck()){
// new ClassPathXmlApplicationContext("spring-quartz.xml");
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
}
}
// initializeMqTTParameters();
// suscribeForAck();
// publishMessage();
}
public void publishMessage(){
try{
// System.out.print("sending ");
Received received=service.getReceivedDataToPublishTMS();
if(received!=null){
System.out.print("sending you not null");
String publisgMSG=createMessageToPublish(received);
pubMessage="lava," ;
publishMessageTms();
}else{
System.out.println("null hora");
}
}catch(Exception ex){
System.out.println("hora"+ex.getLocalizedMessage()+" "+ex.toString());
}
}
}
and here is xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- <bean id="exampleBusinessObject" class="com.ehydromet"/> -->
<!-- Old JobDetail Definition
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="exampleBusinessObject"/>
<property name="targetMethod" value="doIt"/>
</bean>
-->
<!-- Runnable Job: this will be used to call my actual job. Must implement runnable -->
<bean name="myRunnableJob" class="com.ehydromet.controller.MyRunnableJob"></bean>
<!-- New Clusterable Definition -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.ehydromet.schedule.GenericQuartzJob" />
<property name="jobDataAsMap">
<map>
<entry key="batchProcessorName" value="myRunnableJob" />
</map>
</property>
</bean>
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<!-- see the example of method invoking job above -->
<property name="jobDetail" ref="jobDetail"/>
<!-- 10 seconds -->
<property name="startDelay" value="5000"/>
<!-- repeat every 50 seconds -->
<property name="repeatInterval" value="5000"/>
</bean>
<context:component-scan base-package="com.ehydromet.service"/>
<context:component-scan base-package="com.ehydromet.dao"/>
<context:component-scan base-package="com.ehydromet.service.impl"/>
<context:component-scan base-package="com.ehydromet.dao.impl"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ehydromet.entity.Alarms</value>
<value>com.ehydromet.entity.UserData</value>
<value>com.ehydromet.entity.ModemInfo</value>
<value>com.ehydromet.entity.Received</value>
<value>com.ehydromet.entity.Modems</value>
<value>com.ehydromet.entity.AdminLogin</value>
<value>com.ehydromet.entity.UserPolicy</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
</props>
</property>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
</list>
</property>
<!-- Add this to make the Spring Context Available -->
<property name="applicationContextSchedulerContextKey"><value>applicationContext</value></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/ejava" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
Dao classes are #Transactional and #Repository.
in MqttImplement class service object is null i think autowired is not working with Quartz scheduler. Any suggestion????
i think autowired is kind of resolved. but
error is-- org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactory' of bean class [org.springframework.scheduling.quartz.SchedulerFactoryBean]: Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
i am new to it. so may be some foolish mistakes i have done, please have a look.
Have you tried #Autowired without static? Seems weird for me...
From other side you do this:
MqttImplement mqttPublishTms=new MqttImplement();
................
mqttPublishTms.publishMessage();
So, it's new not Dependency Injection. There is no surprise that the service property there is null.
Want to use Spring to automatically work with Hibernate 4 sessions
Also I like to extends DAO, for not create many DAO for many entities
But there is problem:
SessionDAO.java
public abstract class SessionDAO extends HibernateDaoSupport{
public void startSession() {
getSession().beginTransaction();
}
public void closeSession() {
getSession().getTransaction().commit();
}
public void addObject() {
startSession();
getSession().save(this);
closeSession();
}
public Session getSession()
{
return getHibernateTemplate().getSessionFactory().getCurrentSession();
}
}
Values.java
#Entity
#Table
public class Values extends SessionDAO {
private int valuesId;
private double amount;
private Date date;
//...getters, setters, etc
}
dispatcher-servlet.xml
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>entity.Crypto</value>
<value>entity.Values</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#my.****.us-east-1.rds.amazonaws.com:1521:ORCL" />
<property name="username" value="****" />
<property name="password" value="****" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
When start server, receive:
INFO: HHH000206: hibernate.properties not found
When try to load page receive:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
on line
return getHibernateTemplate().getSessionFactory().getCurrentSession();
What's wrong?
Don't get the session by extend HibernateDaoSupport, just inject SessionFactory in DAO.
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
but in my code i'm getting null pointer exception when i'm using session factory for second time . and it is working fine in first .
here is my code
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="url" value="jdbc:mysql://localhost:3306/pdevice"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="show_sql">true</prop>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
<property name="mappingResources">
<array>
<value>/LoginDTO.hbm.xml</value>
</array>
</property>
</bean>
<bean id="loginDAO" class="com.raj.sprmvc.dao.LoginDAOImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="loginManager" class="com.raj.sprmvc.manager.LoginManagerImpl">
<property name="loginDAO" ref="loginDAO"></property>
</bean>
<!-- <bean id="login" class="com.raj.sprmvc.controller.LoginController">
<property name="loginManager" ref="loginManager"></property> </bean> -->
<bean id="commandController" name="/login.do" class="com.raj.sprmvc.controller.LoginController">
<property name="loginManager" ref="loginManager"></property>
<property name="commandClass" value="com.raj.sprmvc.dto.LoginDTO"></property>
<property name="validator" ref="loginValidator"></property>
</bean>
<bean id="loginValidator" class="com.raj.sprmvc.validator.LoginValidator"></bean>
<!-- ++++++++++++++++++++++to update place+++++++++++++++++++++ -->
<bean id="updateUNDAO" class="com.raj.sprmvc.dao.UpdateUNDAOImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="updateManager" class="com.raj.sprmvc.manager.UpdateManagerImpl">
<property name="undao" ref="updateUNDAO"></property>
</bean>
<bean id="commandController1" name="/update.do"
class="com.raj.sprmvc.controller.UpdateController">
<property name="updateManager" ref="updateManager"></property>
<property name="commandClass" value="com.raj.sprmvc.dto.LoginDTO"></property>
<!-- <property name="validator" ref="loginValidator"></property> -->
</bean>
when i'm trying to use sessinfactory for second time it is giving nullpointer ..i know this basic concept but struggling to solve this pls share .......
thanks
this is the first module
public class LoginDAOImpl implements LoginDAO{
private SessionFactory sessionFactory;
#Override
public boolean isExist(LoginDTO ldto) {
Session session=sessionFactory.openSession();
Query query=session.createQuery(" FROM LoginDTO WHERE username='"+ldto.getUsername()+"' AND password='"+ldto.getPassword()+"'");
if(query.uniqueResult()!=null){
return true;
}
return false;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
and in second module
public class UpdateUNDAOImpl implements UpdateUNDAO{
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void update(LoginDTO ldto){
Session session=sessionFactory.openSession();
System.out.println(session);
Transaction tr= session.beginTransaction();
tr.begin();
LoginDTO ldto1=(LoginDTO)session.load(LoginDTO.class, 1);
ldto1.setPlace(ldto.getPlace());
session.update(ldto1);
tr.commit();
session.close();
}
}
in this module the line Session session=sessionFactory.openSession(); is giving null pointer exception
exception
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.27 logs.
exception