hibernate + named query not known - java

I am getting problem while using named query with hibernate and spring.
below is my code and stacktrace.
Method that is calling my query is :
#SuppressWarnings("unchecked")
#Override
public List<CampaignEntity> getCampaignList() {
final Query clientQuery = getNamedQuery(CampaignEntity.GET_CAMPAIGNS_QUERY);
return (List<CampaignEntity>) clientQuery.list();
}
my Entity class is
package com.nativeunlock.dto;
import java.io.Serializable;
import javax.persistence.*;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
#SuppressWarnings("serial")
#NamedQueries({
#NamedQuery(
name = CampaignEntity.GET_CAMPAIGNS_QUERY,
query = "from CampaignEntity campaign"
)
})
#Entity
#Data
#Table(name = "campaign")
public class CampaignEntity implements Serializable {
public static final String GET_CAMPAIGNS_QUERY ="getCampaignList";
#Id
#Getter
#Setter
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "campaingn_id", unique = true, nullable = false)
private int campain_id;
#Getter
#Setter
#Column(name = "no_of_views")
private int no_of_views;
#Getter
#Setter
#Column(name = "video_url")
private int video_url;
}
my xml file is
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<context:component-scan base-package="com.nativeunlock.**" />
<context:property-placeholder location="classpath:common.properties" />
<bean id="dataSource" class="${datasource.class}">
<property name="driverClassName" value="${mysql.driver}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.nativeunlock.dao.**"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="savedRequestAwareAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="targetUrlParameter" value="targetUrl" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<security:global-method-security
jsr250-annotations="enabled" pre-post-annotations="enabled"
secured-annotations="enabled" />
</beans>
my stacktrace is
org.hibernate.MappingException: Named query not known: getCampaignList
at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSess
ionImpl.java:154)
at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:137
1)
at com.nativeunlock.dao.CampaignDao.getNamedQuery(CampaignDao.java:41)
at com.nativeunlock.dao.CampaignDao.getCampaignList(CampaignDao.java:47)
at com.nativeunlock.service.CampaignService.getCampaignList(CampaignServ
ice.java:20)
at com.nativeunlock.security.controller.LoginController.campaign(LoginCo
ntroller.java:31)
at com.nativeunlock.security.controller.LoginController$$FastClassByCGLI
B$$25d5f75b.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocatio
n.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:150)
at org.springframework.security.access.intercept.aopalliance.MethodSecur
ityInterceptor.invoke(MethodSecurityInterceptor.java:64)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterc
eptor.intercept(Cglib2AopProxy.java:622)
at com.nativeunlock.security.controller.LoginController$$EnhancerByCGLIB
$$ac304978_2.campaign(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.
invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(Dispatch
erServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(Dispatche
rServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(Frame
workServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServl
et.java:778)
Can any one help me to find out what wrong am I doing?

It seems that you're not scanning the package where you're named query resides, you scan com.nativeunlock.dao.**
<property name="packagesToScan" value="com.nativeunlock.dao.**"/>
and you're entity is within com.nativeunlock.dto

Related

ConcurrentModificationException when Hibernate Upgrade from 4.x to 5.x and Spring 4.x for Multi-Threaded

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

#ExceptionHandler returns a view instead of a String

I have written the below code in Spring for handling custom exceptions. My Exception handler is executing But it returns a view as shown below instead of a String. May I know what is wrong in my code. Thanks in advance.
Code:
#Controller
public class RestController {
#ExceptionHandler(SpringException.class)
public String handleCustomException(SpringException ex) {
String jsonInString = "{}";
JSONObject json = new JSONObject();
Map<String,String> errorMap = new HashMap<String,String>();
errorMap.put("errorMessage",ex.getMessage());
System.out.println("Inside exception handler");
json.putAll(errorMap);
jsonInString = json.toJSONString();
logger.info(jsonInString);
return jsonInString;
}
#RequestMapping(value = "/v1/dist_list/{emailId}/members", method = RequestMethod.GET)
public #ResponseBody String getDistributionListMember(#PathVariable String emailId) throws Exception, SpringException {
String retStatus = null;
retStatus = dataServices.getDistributionListMember(emailId, callerId);
if (!retStatus.isEmpty()) {
if (retStatus.contains("callerid is not valid")) {
throw new SpringException("Error", retStatus);
}
}
}
SpringException class
package com.uniteid.model;
import org.springframework.http.HttpStatus;
public class SpringException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public SpringException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}
Below is my Spring-config.xml file
<?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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.uniteid.controller" />
<mvc:annotation-driven
content-negotiation-manager="contentNegociationManager" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:uniteidrest.properties" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url">
<value>${eidms.url}</value>
</property>
<property name="username">
<value>${eidms.username}</value>
</property>
<property name="password">
<value>${eidms.password}</value>
</property>
</bean>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"
/> <property name="url" value="jdbc:oracle:thin:#un.org:1521:EIDMSUAT"
/> <property name="username" value="EIDMSUAT" /> <property name="password"
value="NewPass" /> </bean> -->
<bean id="contentNegociationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="ignoreAcceptHeader" value="true" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.uniteid.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.connection.pool_size">10</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name = "exceptionMappings">
<props>
<prop key = "com.uniteid.model.SpringException">
ExceptionPage
</prop>
</props>
</property>
<property name = "defaultErrorView" value = "error"/>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="dataDao" class="com.uniteid.dao.DataDaoImpl"></bean>
<bean id="dataServices" class="com.uniteid.services.DataServicesImpl"></bean>
</beans>

Data entered in product java class is giving exception

Hi I am getting the following Exception in the springMVC application code.. I read some previous question but didn't find any help.
I have two entities in the application i.e.
user
products
Data entered in product java class is giving exception:-
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.onlineshopping.model.Product
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)
Product.java class is :
package com.onlineshopping.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Product")
public class Product implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="productid")
private Integer proid;
#Column(name="productname")
private String proname;
#Column(name="price")
private Integer price;
#Column(name="details")
private String details;
public Integer getProid() {
return proid;
}
public void setProid(Integer proid) {
this.proid = proid;
}
public String getProname() {
return proname;
}
public void setProname(String proname) {
this.proname = proname;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
Configuration File:
<?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/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.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.onlineshopping" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.onlineshopping.model.Customer</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.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Can someone tell me why this exception occur.the other user entity is working correctly.
thanks
so after comment #dhs found answer
session factory needs to setPackagesToScan so do try this adding into annotatedClasses
com.onlineshopping.model.Product
<?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/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.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.onlineshopping" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.onlineshopping.model.Customer</value>
<value>com.onlineshopping.model.Product</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.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>

Spring PropertyPlaceholderConfigurer load from DB

Is it possible to load properties from DB with Custom Spring PropertyPlaceholderConfigurer?
and is it also possible that datasource provided to custom PropertyPlaceholderConfigurer use specific property file in classpath?
I could not find satisfied answer from following links?
http://www.mkyong.com/spring/spring-propertyplaceholderconfigurer-example/
http://www.codeproject.com/Articles/28893/Loading-Application-Properties-from-a-Database
PropertyPlaceholderConfigurer to look for DB values and use properties file as fallback
Spring Context XML
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="false"/>
<property name="order" value="1" />
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<bean id="dataSourceimos" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass"><value>${imosdb.driver}</value></property>
<property name="jdbcUrl"><value>${imosdb.url}</value></property>
<property name="user"><value>${imosdb.username}</value></property>
<property name="password"><value>${imosdb.password}</value></property>
<property name="initialPoolSize"><value>${imosdb.initial_pool_size}</value></property>
<property name="maxPoolSize"><value>${imosdb.max_pool_size}</value></property>
<property name="minPoolSize"><value>${imosdb.min_pool_size}</value></property>
<property name="acquireIncrement" value="1"/>
<property name="acquireRetryAttempts" value="1"/>
<property name="idleConnectionTestPeriod" value="30"/>
<property name="preferredTestQuery" value="select 1 from dual"/>
<property name="checkoutTimeout" value="5000"/>
<property name="maxAdministrativeTaskTime" value="120"/>
<property name="numHelperThreads" value="10"/>
</bean>
<bean
class="com.ahmetk.property.DbPropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="order" value="2" />
<property name="placeholderPrefix" value="${" />
<property name="placeholderSuffix" value="}" />
<property name="dataSourceName" value="dataSourceimos" />
<property name="locations">
<list>
<value>classpath:static.properties</value>
<value>file:static.properties</value>
</list>
</property>
</bean>
<context:component-scan base-package="com.mkyong.rest" />
<bean id="transactionBo" class="com.mkyong.transaction.impl.TransactionBoImpl" />
<bean id="cacheServiceInterface" class="com.ttech.tims.imos.data.cache.CacheServiceImpl" />
<bean id="iCacheService" class="com.ttech.tims.imos.data.cache.impl.CacheService" />
</beans>
Java PlaceholderClass
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class DbPropertySourcesPlaceholderConfigurer extends PropertyPlaceholderConfigurer
{
private static final String DEFAULT_DATASOURCENAME = "dataSource";
private static final String DEFAULT_DBTABLENAME = "property";
private static final String DEFAULT_DBKEYCOLUMNNAME = "key";
private static final String DEFAULT_DBVALUECOLUMNNAME = "value";
String dataSourceName;
String dbTableName;
String dbKeyColumnName;
String dbValueColumnName;
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
DataSource dataSource = (DataSource) beanFactory.getBean(getDataSourceName());
// DbProperties dbProps = new DbProperties(dataSource);
final Properties dbProps = new Properties();
dbProps.put("app.version", "v3");
setProperties(dbProps);
super.postProcessBeanFactory(beanFactory);
}
public String getDataSourceName() {
return dataSourceName==null?DEFAULT_DATASOURCENAME:dataSourceName;
}
public void setDataSourceName(String dataSourceName) {
this.dataSourceName = dataSourceName;
}
}
Special thanks to writer of following pages.
http://ykchee.blogspot.com.tr/2012/09/spring-31-loading-properties-for-xml.html
http://blog.javaforge.net/post/31720600427/configuring-spring-based-web-application-from-database
http://www.javacodegeeks.com/2012/11/spring-3-1-loading-properties-for-xml-configuration-from-database.html

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