Java NoSuchMethodException In Spring (While I have created a constructor) - java

I would like to ask about where did I go wrong in this. I just started up a simple login feature using Spring and Hibernate 4, but it seems that I always seem to get NoSuchMethodException. Tried looking up everywhere about where I go wrong, but it's like I never did get it right. Any help will be most appreciated. Below are the Codes.
bean.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"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="try*">PROPAGATION_REQUIRED,ISOLATION_READ_UNCOMMITTED,-Exception</prop>
<!-- <prop key="try*">PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE,-Exception</prop> -->
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:#db01.aprdev.com:1521:aprdev" />
<property name="username" value="training" />
<property name="password" value="training" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://localhost:1433;databaseName=test" />
<property name="username" value="sa" />
<property name="password" value="pass123" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>com/model/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> -->
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
</bean>
<bean id="userDAO" class="com.dao.impl.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="serviceProxyTemplate" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="userServiceProxy" parent="serviceProxyTemplate">
<property name="target">
<bean id="userService" class="com.services.impl.UserServiceImpl">
<property name="userDAO" ref="userDAO" />
</bean>
</property>
</bean>
User.java
package com.model;
public class User {
private String id;
private String name;
private String password;
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserServiceImpl.java
package com.services.impl;
import java.util.List;
import com.dao.UserDAO;
import com.model.User;
import com.services.UserService;
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
public List validate(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return this.userDAO.validate(user);
}
}
UserDAOImpl.java
package com.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.dao.UserDAO;
import com.model.User;
public class UserDAOImpl implements UserDAO{
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory session) {
this.sessionFactory = session;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public List validate(User user) throws HibernateException {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where name = :name and password = :pass ");
query.setParameter("name", user.getName());
query.setParameter("pass", user.getPassword());
return query.list();
}
}
Test.java
package com.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.services.UserService;
public class SpringUtil {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext(){
if(applicationContext==null){
applicationContext = new ClassPathXmlApplicationContext("com/factory/bean.xml");
}
return applicationContext;
}
public static UserService getUserService(){
return (UserService) getApplicationContext().getBean("userServiceProxy");
}
}
Help will be much appreciated. Thank you very much!

Not sure if I've answered the problem.
Here is my test
package com.services.impl;
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.model.User;
import com.model.UserDAO;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext-test.xml")
public class StudyPointRepositoryTest {
#Autowired
private UserServiceImpl userService;
#Autowired
private UserDAO dao;
#Test
#Transactional
public void test1() {
dao.save(makeUser("Fred", "pass1"));
dao.save(makeUser("Bill", "pass2"));
dao.save(makeUser("Nobby", "pass3"));
List<User> validate = userService.validate("Fred", "pass1");
assertEquals(1, validate.size());
validate = userService.validate("Fred", "wrongpass");
assertEquals(0, validate.size());
}
private User makeUser(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return user;
}
}
Here is my config for test
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com" />
<jdbc:embedded-database id="dataSource" type="H2" />
<tx:annotation-driven />
<jpa:repositories base-package="com.model" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
Here is my DAO
package com.model;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserDAO extends CrudRepository<User, Integer> {
List<User> findByNameAndPassword(String name, String password);
}
Here is my Service
package com.services.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.User;
import com.model.UserDAO;
#Service
public class UserServiceImpl {
#Autowired
private UserDAO userDAO;
public List<User> validate(String name, String password) {
return userDAO.findByNameAndPassword(name, password);
}
}
And here is my pom, probable stuff that not needed
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.greg</groupId>
<artifactId>jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>fmis Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<spring.data.version>1.9.2.RELEASE</spring.data.version>
<hibernate.version>5.0.6.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.190</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>jpaTest</finalName>
</build>
</project>

Related

Spring 4 and hibernate 5 integration

I am currently trying to integrate hibernate with spring.I am using the dao design patter and mysql as database.
i am trying to add the contacte entity in the db but i got this error
Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1165)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:643)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:640)
at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:359)
at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:326)
at org.springframework.orm.hibernate5.HibernateTemplate.save(HibernateTemplate.java:640)
at biz.picosoft.daoImpl.ContacteDaoImpl.inserteContacte(ContacteDaoImpl.java:20)
at biz.picosoft.mains.TestHibernate.main(TestHibernate.java:21)
this is my context 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mailmaneger" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mysessionFactory" />
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="biz.picosoft.daoImpl.ContacteDaoImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
my main file
package biz.picosoft.mains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import biz.picosoft.daoImpl.ContacteDaoImpl;
import biz.picosoft.entity.Contacte;
public class TestHibernate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Contacte contacte=new Contacte("fatma", "test", "test", "test");
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
ContacteDaoImpl contacteDaoImpl=(ContacteDaoImpl) context.getBean("d");
contacteDaoImpl.inserteContacte(contacte) ;
}
}
my dao file
package biz.picosoft.daoImpl;
import java.util.List;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import biz.picosoft.entity.Contacte;
public class ContacteDaoImpl implements ContacteDao{
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void inserteContacte(Contacte contacte) {
// TODO Auto-generated method stub
template.save(contacte);
}
public void updateContacte(Contacte contacte) {
// TODO Auto-generated method stub
template.update( contacte );
}
public void deleteContacte(Contacte contacte) {
// TODO Auto-generated method stub
template.delete(contacte);
}
public Contacte getContacteById(int id) {
// TODO Auto-generated method stub
return template.get(Contacte.class, id);
}
public List<Contacte> getAll() {
// TODO Auto-generated method stub
return template.loadAll(Contacte.class);
}
public HibernateTemplate getTemplate() {
return template;
}
}
my Entity file
package biz.picosoft.entity;
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 = "Contacte")
public class Contacte {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "idContact")
long idContact;
#Column(name = "nom")
String nom;
#Column(name = "mail")
String mail;
#Column(name = "téléphone")
String téléphone;
#Column(name = "adresse")
String adresse;
public Contacte( String nom, String mail, String téléphone, String adresse) {
super();
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
}
public long getIdContact() {
return idContact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTéléphone() {
return téléphone;
}
public void setTéléphone(String téléphone) {
this.téléphone = téléphone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (idContact ^ (idContact >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contacte other = (Contacte) obj;
if (idContact != other.idContact)
return false;
return true;
}
}
my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd
http://www.springframework.org/schema/context/spring-context.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.picosoft.gestionCourrier</groupId>
<artifactId>gestion-courrier</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>maven.alfresco.com</id>
<name>Alfresco Maven Repository</name>
<url>http://maven.alfresco.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring</artifactId>
<version>5.14</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-engine</artifactId>
<version>5.14</version>
</dependency>
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>0.9</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>0.2</version>
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
Most probably you missed to trigger transaction. In your context.xml add <tx:annotation-driven/> for declarative transaction support. And add #Transactional(readOnly=false) over the ContacteDaoImpl methods.
This should solve your problem. If not, there might be something else.
i fixed this problem by changing those beans,but it seems it is like creating the tables but values are not added in the table
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
<property name="checkWriteOperations" value="false"></property>
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="packagesToScan" value="biz.picosoft.entity"/>
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

Spring #Autowired annotation doesn't work in Java TimerTask

How to change my code to make it work?
public class GetDataFromTheWarehouse implements ServletContextListener {
#Autowired
ScheduledTask scheduledTask;
private ScheduledExecutorService scheduler = null;
public GetDataFromTheWarehouse() {
}
public void contextDestroyed(ServletContextEvent arg0) {
try {
System.out.println("Scheduler Shutting down successfully " + new Date());
scheduler.shutdown();
} catch (Exception ex) {
}
}
public void contextInitialized(ServletContextEvent arg0) {
if ((scheduler == null) || (!scheduler.isTerminated())) {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(scheduledTask, 0, 60*60, TimeUnit.SECONDS);
}
}
}
Following is the ScheduledTask class, in which productService is null, so will fail every time calling productService.save():
#Component
public class ScheduledTask extends TimerTask {
#Autowired
ProductService productService;
public void run() {
try {
parse();
} catch (IOException e) {
e.printStackTrace();
}
}
public void parse() throws IOException {
...
productService.save(product);
...
}
}
}
My applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
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/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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable autowire -->
<context:component-scan base-package="com" />
<context:annotation-config />
<bean id="usersUpdateTask" class="com.demo.task.ScheduledTask">
</bean>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/views/**" location="/views/" />
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/fonts/**" location="/fonts/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/demo" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Session Factory Declaration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.demo.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.default_schema">demo</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My demo structure:
Why do you have ScheduledTask initialized in appilcationConfig.xml when you are already using #Component for that bean class. Remove this from your applicationContext.xml file.
<bean id="usersUpdateTask" class="com.demo.task.ScheduledTask">
</bean>
EDIT : Adding Spring Boot Sample.
Here is the sample code for #Scheduled with #Autowired in Spring Boot.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot-scheduler</groupId>
<artifactId>springboot-scheduler-app</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
</project>
MySpringBootApp.java
package my.spring.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#EnableScheduling
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(new Object[] { MySpringBootApp.class }, args);
}
}
MyService.java
package my.spring.app;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Component;
#Component
public class MyService {
public String getNextMessage(){
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date());
}
}
ScheduledTask.java
package my.spring.app;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class ScheduledTask {
#Autowired
MyService service;
#Scheduled(fixedRate = 5000)
public void process() {
System.out.println("Processing at " + service.getNextMessage());
}
}
Sample output
Processing at 2016-08-24T14:01:48
Processing at 2016-08-24T14:01:53
Processing at 2016-08-24T14:01:58
Hope this helps.
EDIT-2 : Adding Spring Boot Sample war file version. Tested with Tomcat 8.
Following two files are changed. Others are same as above.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot-scheduler</groupId>
<artifactId>springboot-scheduler-app</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
MySpringBootApp.java
package my.spring.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#EnableScheduling
public class MySpringBootApp extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MySpringBootApp.class);
}
public static void main(String[] args) {
SpringApplication.run(new Object[] { MySpringBootApp.class }, args);
}
}

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.

How to resolve Error creating bean with name 'sessionFactory' defined in ServletContext resource in Hibernate4

I am using Hibernate4 in my application for multitenancy implementation while building application war i got following error in my catalina of tomcat.
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field:
protected org.hibernate.SessionFactory com.boxco.blip.dao.BaseDao.sessionFactory;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]:
Invocation of init method failed; nested exception is java.lang.NullPointerException
Here is my application -persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
<context:annotation-config />
<tx:annotation-driven />
<context:component-scan base-package="com.boxco.blip">
</context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/blip</value>
</property>
<property name="resourceRef">
<value>true</value>
</property>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.boxco.blip.model.Address</value>
</list>
</property>
<property name="hibernateProperties">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.show_sql" value="true" />
<entry key="hibernate.connection.autocommit" value="false" />
<entry key="hibernate.jdbc.batch_size" value="0" />
<entry key="hibernate.connection.release_mode" value="after_transaction" />
<entry key="hibernate.multiTenancy" value="SCHEMA" />
<entry key="hibernate.tenant_identifier_resolver" value-ref="multiTenantIdentifierResolver1" />
<entry key="hibernate.multi_tenant_connection_provider" value-ref="multiTenantConnectionProvider1" />
</map>
</property>
</bean>
<bean id="multiTenantConnectionProvider1" class="com.boxco.blip.web.util.SchemaMultiTenantConnectionProviderBlip">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="multiTenantIdentifierResolver1" class="com.boxco.blip.web.util.SchemaCurrentTenantIdentifierResolverBlip" />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
MY AddressDao.java File
package com.boxco.blip.dao;
import com.boxco.blip.model.Address;
public interface AddressDao {
public Address getAddressByAddressId(int addressId);
}
My AddressDaoImpl.java file
package com.boxco.blip.dao;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.boxco.blip.model.Address;
#Component
#Repository(value = "addressDao")
public class AddressDaoImpl extends BaseDao implements AddressDao {
private static final Logger logger = Logger.getLogger(AddressDaoImpl.class);
#Override
public Address getAddressByAddressId(int addressId) {
logger.info("Entering getAddressByAddressId()........");
Address address = null;
Criteria criteria = getSession().createCriteria(Address.class);
criteria.add(Restrictions.eq("addressId", addressId));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
address = (Address)criteria.uniqueResult();
logger.info("Exiting getAddressByAddressId()..........");
return address;
}
}
My Base Dao file where i init sessionFactory object:
package com.boxco.blip.dao;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.mysql.jdbc.Connection;
public abstract class BaseDao
{
#Autowired
#Qualifier("sessionFactory")
protected SessionFactory sessionFactory;
protected void init(SessionFactory factory) {
try {
setSessionFactory(factory);
} catch (Exception e) {
e.printStackTrace();
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() throws HibernateException {
// return sessionFactory.getCurrentSession();
return sessionFactory.withOptions().tenantIdentifier("BLIP1314ERP")
.openSession();
}
//some more methods
}
My Dispatcher-servlet.xml file where is added
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
<mvc:annotation-driven/>
<context:component-scan base-package="com.boxco">
<!-- <context:exclude-filter type="regex" expression="com.boxco.blip.dao.*" /> -->
</context:component-scan>
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basenames" value="views"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<value>messages,error_codes</value>
</property>
</bean>
<bean id="validatorFactory"
class="org.springmodules.validation.commons.DefaultValidatorFactory">
<property name="validationConfigLocations">
<list>
<value>/WEB-INF/validator-rules.xml</value>
<value>/WEB-INF/validator.xml</value>
<value>/WEB-INF/validatorFas.xml</value>
<value>/WEB-INF/validatorFas-rules.xml</value>
</list>
</property>
</bean>
<bean id="validator" class="org.springmodules.validation.commons.DefaultBeanValidator">
<property name="validatorFactory" ref="validatorFactory"/>
</bean>
Error is in my SessionFactory initialization but why it is not getting init is my problem..?
(I am handling this error first time)..
Any suggestion appreciated.
It shouldn't be your solution, in any case the #component annotation over #repository is useless. Either you insert #repository (better for exception translation) or #component.
I resolved it by replacing my JAR files from 4.3.4 to 4.1.7 (downgraded my jar) hibernate version ,I dont know why its not working with latest versions of Hibernate

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