HibernateException: save is not valid without active transaction - java

So I thoroughly went through
Get is not valid without active transaction
and know I don't have the problem of not autowiring the SessionFactory and have followed best practices but still am encountering this exception:
org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at com.sun.proxy.$Proxy31.save(Unknown Source)
at com.bms.dao.DemandManageDAOImpl.save(DemandManageDAOImpl.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy29.save(Unknown Source)
at com.bms.service.DemandServiceImpl.createDemand(DemandServiceImpl.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy30.createDemand(Unknown Source)
at com.bms.dao.DemandManageDAO_UT.testCreateDemand(DemandManageDAO_UT.java:69)
Which I will try to include all the necessary config and code which is spread over multiple files. Sorry for all the files and thank you in advance.
This is Java 1.7, Spring 4.0.2.RELEASE, Hibernate 4.3.5.Final
Seems like this was routine with previous versions. I can get around this by getting a session and beginning a transaction but I don't want to do that.
context:
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Database Configuration -->
<import resource="classpath:database/hibernate.xml"/>
<!-- Auto scan the components -->
<context:component-scan base-package="com.bms" />
<tx:annotation-driven/>
<bean id="demandManageDao" class="com.bms.dao.DemandManageDAOImpl"></bean>
<bean id="demandService" class="com.bms.service.DemandServiceImpl"> </bean>
</beans>
hibernate.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<import resource="classpath:database/dataSource.xml" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database/database.${demandEnv}.properties</value>
</property>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.bms.demand.domain.data</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.autocommit">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
datasource.xml
<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-2.5.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database/database.${demandEnv}.properties</value>
</property>
</bean>
<!-- HSQLDB Data Source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
</beans>
test file:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:applicationContext.xml"})
#TransactionConfiguration(transactionManager = "transactionManager",defaultRollback=true)
#Transactional
public class DemandManageDAO_UT {
private static ApplicationContext context;
private SessionFactory sessionFactory;
private DemandManageDAO demandManageDAO;
private DemandService demandService;
#BeforeClass
public static void setUpClass(){
context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
#Before
public void setUp() throws Exception {
demandManageDAO = (DemandManageDAO)context.getBean("demandManageDao");
demandService = (DemandService)context.getBean("demandService");
sessionFactory = (SessionFactory)context.getBean("sessionFactory");
}
#After
public void tearDown() throws Exception {
}
#Test
public void testCreateDemand() throws Exception {
Demand myDemand2 = new Demand();
myDemand2.setId(10L);
myDemand2.setDescription("text");
myDemand2.setMonths(1);
Calendar calendar = Calendar.getInstance();
calendar.set(2000, 7, 4);
myDemand2.setStartDate(calendar.getTime());
Availibility availibility = new Availibility();
availibility.setId(2L);
availibility.setMonth(calendar.getTime());
availibility.setPercentage(new Integer(50));
availibility.setResourceName("text");
myDemand2.addAvailibility(availibility);
Long perId = demandService.createDemand(myDemand2);
assertThat(perId,is(myDemand2.getId()));
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Availibility sessionObject = (Availibility) session.get(Availibility.class, 2L);
assertThat(sessionObject.getResourceName(),is("text"));
}
}
serviceImpl
#Component
public class DemandServiceImpl implements DemandService {
#Autowired
DemandManageDAO demandManageDao;
public void setDemandManageDao(DemandManageDAO demandManageDAO) {
this.demandManageDao = demandManageDAO;
}
#Override
#Transactional
public Long createDemand(Demand myDemand2) throws Exception {
return demandManageDao.save(myDemand2);
}
}
the DAO
#Repository
public class DemandManageDAOImpl implements DemandManageDAO {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Override
public Long save(Demand myDemand) throws Exception {
return (Long) getCurrectSession().save(myDemand);
}
private Session getCurrectSession() {
return getSessionFactory().getCurrentSession();
}
}

You can't use auto-commit with transactions, the connections need to be managed by the Transaction Manager instead, so remove these line:
<prop key="hibernate.connection.autocommit">true</prop>
Also you might want to add:
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property><prop

Related

Getting null pointer exception while using abstract factory pattern in spring-mvc [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 6 years ago.
Its the First time i am integrating spring with hibernate, When i
invoke any method of Dao class i am getting null pointer Exception
I am using abstract factory pattern Source code of Abstract class :
public abstract class Content {
#Autowired
HibernateOperations ho;
#Transactional
public List<ContentDes> getContentDes(String sql,int limit){
//do it with autowired
List<Object[]> ls = new ArrayList<Object[]>();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
System.out.println("--before invoking method---");
ho.just_print();
ls = ho.getResultListByLimit(sql,limit);
for(Object[] obj: ls){
ContentDes contentDes = new ContentDes();
contentDes.setCode((String)obj[0]);
contentDes.setContent_prv((String)obj[1]);
contentDes.setPricetag((String)obj[2]);
contentDes_ls.add(contentDes);
}
return contentDes_ls;
}
abstract List<ContentDes> getRandomContent(int limit);
//abstract List<ContentDes> getDistinctCat();
}
And i have five class that are extending my Content Class: coding of
one of my child id liem below:
public class Wallpaper extends Content{
#Override
public List<ContentDes> getRandomContent(int limit) {
String sql = "select code,prv,pricetag from Wallpaper where cat not like 'Holy Deities' order by rand() limit "+limit+"";
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
contentDes_ls = getContentDes(sql,limit);
return contentDes_ls;
}
}
And class which returning clasess obects according to the content type
is :
public class GetContentFactory {
//use getContent method to get object of type Content
public Content getContent(String contentType) {
contentType = contentType.toLowerCase();
if (contentType.equalsIgnoreCase("wallpaper")) {
return new Wallpaper();
} else if (contentType.equalsIgnoreCase("animation")) {
return new Animation();
} else if (contentType.equalsIgnoreCase("ringtone")) {
return new Ringtone();
} else if (contentType.equalsIgnoreCase("video")) {
return new Video();
}
else if (contentType.equalsIgnoreCase("game")) {
return new Game();
}
else {
System.out.println(" unknow request in GetContentFactory class");
}
return null;
}
}//end of GetContentFactory class.
My main class is :
public class GetContent {
GetContentFactory contentFactory = new GetContentFactory();
}
public List<ContentDes> getRandomContent(String content_type, int limit) {
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
Content con = contentFactory.getContent(content_type);
contentDes_ls = con.getRandomContent(limit);
for (ContentDes contentDes : contentDes_ls) {
System.out.println("prv----"+contentDes.getContent_prv());
}
return contentDes_ls;
}
}
Code of my dao class is :
#Repository
public class HibernateOperations {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
//pass the sql query to get result for multiple column
public List<Object[]> getResultListByLimit(String query,int limit){
System.out.println("in get result-------");
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
Query q = session.createQuery(query);
q.setMaxResults(limit);
ls_ob = (List<Object[]>)q.list();
return ls_ob;
}
public List<Object> getListForSingleColumn(String query){
Session session = this.sessionFactory.getCurrentSession();
List<Object> ls_ob = new ArrayList<Object>();
Query q = session.createQuery(query);
ls_ob = q.list();
return ls_ob;
}
public void SaveObject(Object obj){
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
session.save(obj);
}
public void just_print(){
System.out.println("---------in method hibenate operation------");
}
}
when My controller class methods call:
GetContent gc = new GetContent();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
contentDes_ls = gc.getRandomContent("wallpaper", 3);
i got an exception:
its prints the
--before invoking method---(its is the sout of my content class method Name "getContentDes")
Apr 25, 2016 6:03:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DefaultServlet] in context with path [/slwap_sh] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at lanka.content.get.Content.getContentDes(Content.java:37)
at lanka.content.get.Wallpaper.getRandomContent(Wallpaper.java:45)
at lanka.content.controller.ContentController.sriWap(ContentController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
I am unable to call any of my Dao Class methods i got null pointer
when i called any method of my Dao(HibernateOperations.java) Class
Can anyone please help me to find out my mistake
coding of DefaultServlet-servlet.xml is like below:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.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">
<mvc:annotation-driven />
<mvc:annotation-driven enable-matrix-variables="true" />
<context:component-scan base-package="lanka.content.controller" />
<context:component-scan base-package="lanka.content.domain" />
<context:component-scan base-package="lanka.content.utility" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- start of languages xml code -->
<!-- lang param is defined in the mvc interceptor -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/propFiles/content" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<!-- end of languages xml code -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptor>
<!-- <mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/resources/**"/>
<bean id="storingWapHits"
class="vodafone.interceptor.StroringHits">
</bean>
</mvc:interceptor> -->
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/design/" />
<!-- start of hibernate integration -->
<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/wapsite" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- hibernate4AnnotatedSessionFactory is a session fectory-->
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>lanka.content.table.Game</value>
<value>lanka.content.table.Scrsaver</value>
<value>lanka.content.table.Video</value>
<value>lanka.content.table.Wallpaper</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
<!-- <bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<property name="personDAO" ref="personDAO"></property>
</bean>-->
<bean id="HibernateOperations" class="lanka.content.utility.HibernateOperations">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
</beans>
By doing :
new Wallpaper();
You are not letting spring do his work, that is to say inject things in your objects :
#Autowired
HibernateOperations ho;
ho will always be null.
Every Content subclasses should be spring beans, and you have to get rid of your GetContentFactory, and only autowire every single spring bean
EDIT : Abstract Factory Design
Define your beans like this :
#Component
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Wallpaper extends Content {
Declare the GetContentFactory as a spring bean as well :
#Component
public class GetContentFactory {
#Autowired
private Wallpaper wallpaper;
This has to be avoided as well :
GetContentFactory contentFactory = new GetContentFactory();

spring Quartz scheduler not accessing database

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.

HIBERNATE : TransactionRequiredException: Executing an update/delete query after entityManager.createNativeQuery()

I'm working on a project using Struts, Spring and Hibernate. After clicking on a button, the Struts action leads me through a DS and DAO, in which I try to call a native query to update the DB. Here is the error trace:
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.ejb.QueryImpl.executeUpdate(QueryImpl.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:618)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:310)
at $Proxy496.executeUpdate(Unknown Source)
at com.my.project.MyDAO.unsubscribe(MyDAO.java:307)
at com.my.project.MyDS.unsubscribe(MyDS.java:507)
at com.my.project.MyDS.updateValue(MyDS.java:784)
at com.my.project.MyAction.handleUpdate(MyAction.java:235)
MyDAO :
public class MyDAO extends
AbstractDAOGenericImpl<MyEntity> {
/** Entity Manager */
#PersistenceContext(unitName = "myPersistenceUnit")
private EntityManager entityManager;
#Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public int unsubscribe(String entityId) throws JrafDaoException {
StringBuilder strQuery = new StringBuilder();
strQuery.append("update MYENTITY set SUBSCRIBE=:subscribe where ENTITY_ID=:entity_id");
final Query myQuery = getEntityManager().createNativeQuery(strQuery.toString(), MyEntity.class);
myQuery.setParameter("subscribe", "N");
myQuery.setParameter("entity_id", entityId);
try {
return myQuery.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
In MyDS :
#Autowired
#Qualifier("MyDAO")
private MyDAO myDao;
#Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public int unsubscribe(String entityId) throws JrafDomainException {
return myDao.unsubscribe(entityId);
}
MyAction :
public class MyAction extends DispatchAction {
private MyDS myDS;
// ...
private ActionForward handleUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
MyForm myForm = (MyForm) form;
myDS.unsubscribe(myForm.getEntityId());
}
}
And application-context-spring.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<!-- Enterprise layer's dependencies -->
<bean id="springLocator"
class="com.jraf.bootstrap.locator.SpringLocator">
</bean>
<!-- To precise the persistence configuration name file -->
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>/META-INF/persistence-web.xml</value>
</list>
</property>
</bean>
<!-- EntityManagerFactory definition : JPA one -->
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager"
ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="myPersistenceUnit" />
</bean>
<!-- TransactionManager JPA one -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<!-- EntityManagerFactory definition : JPA one -->
<bean id="myEmf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="myPersistenceUnit2" />
</bean>
<!-- Transaction Manager definition : JPA one-->
<bean id="myTxManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf2" />
</bean>
<!-- Enable annotation usage for transaction -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="1" />
<property name="maxPoolSize" value="1" />
<property name="queueCapacity" value="1" />
</bean>
<bean id="myDS" class="com.my.internal.MyDS">
<property name="myDao" ref="MyDAO"/>
</bean>
<!-- Enable the annotation usage (bean injection for instance) -->
<context:annotation-config />
</beans>
I'm working on an existing project which is why the unsubscribe function already exists and uses a native query instead of a HQL one. But maybe I should use it instead...?
Thanks for your help.
I also faced the similar issue.
Adding
tx:annotation-driven transaction-manager="transactionManager"
to your spring context xml will resolve the issue.

Spring + Hibernate console application

Some prehistory..
I have a web-based corporate CRM system written with Spring and Hibernate. There are a lot of tasks that should be done systematically such as reminders or email notifications.. Now it is implemented as a separate Controller wich is called from cron. Everything works fine except of the fact that some of tasks are very "heavy" and take a lot of Tomcat's resources. So I decided to split them into different java console apps. In order to use the same objects and services I splited the main project into separate projects (libraries):
Objects
DAO
In the main project I just added these projects to the BuildPath so I can use all the objects and services without any problem.
Now I started implement the first console utility and facing some issue.. Take a look.
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-service.xml", "spring-hibernate.xml");
try {
MessageSourceEx messageSource = new MessageSourceEx((ResourceBundleMessageSource) ctx.getBean("messageSource"));
ITasksService tasksService = (ITasksService) ctx.getBean("tasksService");
NotificationsService notificationsService = (NotificationsService) ctx.getBean("notificationsService");
List<Task> tasks = tasksService.systemGetList();
for (Task t: tasks) {
Locale userLocale = t.getCreator().getCommunicationLanguageLocale();
EmailNotification reminder = new EmailNotification(t.getCreator().getEmail(),
messageSource.getMessage(userLocale, "notifications.internal.emails.task.subject"),
messageSource.getMessage(userLocale, "notifications.internal.emails.task.text",
t.getCreator().getNickname(),
t.getName(),
t.getDescription(),
AppConfig.getInstance().getUrl(),
t.getId()),
userLocale, t.getCreator());
notificationsService.email.send(reminder);
if (reminder.getState() == EmailNotificationSendState.Sent) {
t.setReminderSent(true);
tasksService.save(t);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
((ConfigurableApplicationContext)ctx).close();
}
System.exit(0);
}
spring-service.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.dao,com.service,com.notifications,com.interfaces" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="com.Resources" />
</bean>
</beans>
spring-hibernate.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<tx:annotation-driven />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/hibernate.properties" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${hibernate.connection.driver_class}" />
<property name="url" value="${hibernate.connection.url}" />
<property name="username" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.data.Task</value>
</list>
</property>
<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_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
DAO
#Component
public class TasksDAO {
/**
* Retrieves a list of tasks
*
* #return List of tasks
*/
#SuppressWarnings({ "unchecked" })
public List<Task> systemGetList() {
Session session = SessionFactoryUtils.getSession(sessionFactory, false);
List<Task> result = null;
Date now = new Date();
Criteria query = session.createCriteria(Task.class)
.add(Restrictions.le("remindTime", DateUtilsEx.addMinutes(now, 3)))
.add(Restrictions.eq("reminderSent", false))
.addOrder(Order.asc("remindTime"));
result = query.list();
if (result == null)
result = new ArrayList<Task>();
return result;
}
}
Service
#Service
public class TasksService implements ITasksService {
/**
*
*/
#Override
public List<Task> systemGetList() {
return tasksDAO.systemGetList();
}
}
It fails with No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SessionFactoryUtils.doGetSession(SessionFactoryUtils.java:356) exception.. What is interesting - if I add #Transactional to systemGetList() - works fine. But I don't want to add transactions for all select statements...
And the same code (without transaction) works fine on web-site itself..
Any help? Thank you in advance.
You have specified your service methods to be Transactional
<tx:annotation-driven />
Add #Transactional(readOnly = true) on select/read only methods

Hibernate object not mapped exception

having some issues with the HQL statement to retrieve all Groups from my database.
I get the following exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: Group is not mapped [from Group]
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3291) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3180) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80) ~[hibernate-core-4.1.6.Final.jar:4.1.6.Final]
Here's the relevant code:
GroupServiceDaoImpl:
public List<Group> getGroups() {
List list = getSessionFactory().getCurrentSession().createQuery("from Group").list();
return (List<Group>) list;
}
spring-hibernate.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Beans Declaration -->
<bean id="User" class="com.youthministry.domain.User"/>
<bean id="UserProfile" class="com.youthministry.domain.UserProfile"/>
<bean id="Event" class="com.youthministry.domain.Event"/>
<bean id="Group" class="com.youthministry.domain.Group"/>
<bean id="Role" class="com.youthministry.domain.Role"/>
<bean id="Location" class="com.youthministry.domain.Location"/>
<bean id="Image" class="com.youthministry.domain.Image"/>
<bean id="PageContent" class="com.youthministry.domain.PageContent"/>
<bean id="TextEntry" class="com.youthministry.domain.TextEntry"/>
<!-- User Service Declaration -->
<bean id="UserService" class="com.youthministry.service.impl.UserServiceImpl">
<property name="userDao" ref="UserDao" />
</bean>
<bean id="GroupService" class="com.youthministry.service.impl.GroupServiceImpl">
<property name="groupDao" ref="GroupDao" />
</bean>
<!-- User DAO Declaration -->
<bean id="UserDao" class="com.youthministry.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="GroupDao" class="com.youthministry.dao.impl.GroupDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="EventDao" class="com.youthministry.dao.impl.EventDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="PageContentDao" class="com.youthministry.dao.impl.PageContentDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<!-- Data Source Declaration -->
<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/YouthMinistry"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.youthministry.domain.Event</value>
<value>com.youthministry.domain.Group</value>
<value>com.youthministry.domain.Image</value>
<value>com.youthministry.domain.Location</value>
<value>com.youthministry.domain.PageContent</value>
<value>com.youthministry.domain.Role</value>
<value>com.youthministry.domain.TextEntry</value>
<value>com.youthministry.domain.User</value>
<value>com.youthministry.domain.UserProfile</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
c:_-ref="dataSource" />
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- Transaction Manager is defined -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
</beans>
Group:
package com.youthministry.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity(name="GROUP_DETAILS")
public class Group {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long groupId;
private String groupName;
private String groupDesc;
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupDesc() {
return groupDesc;
}
public void setGroupDesc(String groupDesc) {
this.groupDesc = groupDesc;
}
}
Just in case here is the git repo for this project:
http://github.com/dmcquillan314/YouthMinistryHibernate
Let me know if any other information about this error is needed and I'll edit the post.
Any ideas are greatly appreciated. Thanks in advance.
You have overridden the default entity name, which would have been the simple name of the class, in the Group class:
#Entity(name="GROUP_DETAILS")
Therefore you cannot use Group as entity name in your query. There are two options to fix that:
If you use "GROUP_DETAILS" in your HQL, the query should succeed. Alternatively you can omit the name attribute of the Entity annotation and keep the HQL as it is.

Categories

Resources