I have an issue with getting session on anonymus inner class in hibernate with spring session factory.
Here is the code:
public class DomainDaoImpl extends BasicDaoImpl<Domain> implements Iterable<Collection<Domain>> {
...
#Override
public Iterator<Collection<Domain>> iterator() {
return (new Iterator<Collection<Domain>>() {
private int counter = 0;
public static final int LIMIT = 100;
...
#Override
#Transactional(readOnly = true)
public Collection<Domain> next() {
final Criteria criteria = getCurrentSession().createCriteria(Domain.class);
final LinkedHashSet<Domain> result = new LinkedHashSet<Domain>();
List resultList = null;
while (!(resultList = criteria.list()).isEmpty()) {
criteria.setFirstResult((counter++ * LIMIT) + 1);
criteria.setMaxResults(LIMIT);
result.addAll(resultList);
}
return result;
}
...
});
The issue is org.hibernate.HibernateException: No Session found for current thread
this happens usually when DAO method is not within transaction.
So how to make it work with an inner class?
i think defining #Transactional(readOnly = true) at inner class level, spring will not be able to detect and apply transaction aspect over it. so it will not work for sure.
but i think if you write something like below might work not 100% sure (i doubt once you invoke iterator method transaction is closed)
#Override
#Transactional(readOnly = true)
public Iterator<Collection<Domain>> iterator() {
...
}
another option can be let caller be responsible for transaction or write wrapper method over iterator() like getAllDomain() and apply transaction to that method.
Solution which worked (mentioned in comments)
may be you can do some patch in getCurrentSession() like
getCurrentSession() from sessionFactory if not available then use
openSession(), ofcourse you have to close it manually if new session
opened.
You can configure load-time aspect weaving
Here is the basic example how to do it
Spring context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:component-scan base-package="org.foo.bar" />
<context:annotation-config />
<context:load-time-weaver />
<tx:annotation-driven mode="aspectj" proxy-target-class="true"/>
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:schema.sql"/>
</jdbc:embedded-database>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>org.foo.bar.MyEntity</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Entity class
package org.foo.bar;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ENTITY")
public class MyEntity {
#Id
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("MyEntity");
sb.append("{id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
Dao class
package org.foo.bar;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Iterator;
import java.util.NoSuchElementException;
#Component
public class MyEntityDao implements Iterable<MyEntity> {
#Autowired
private SessionFactory sessionFactory;
#Override
public Iterator<MyEntity> iterator() {
return new Iterator<MyEntity>() {
private int num = 0;
private MyEntity item;
#Override
#Transactional(readOnly = true)
public boolean hasNext() {
item = getEntity();
return item != null;
}
#Override
#Transactional(readOnly = true)
public MyEntity next() {
try {
if(item == null) {
item = getEntity();
if(item == null) {
throw new NoSuchElementException();
}
}
return item;
} finally {
item = null;
}
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
private MyEntity getEntity() {
final Criteria criteria = getCurrentSession().createCriteria(MyEntity.class);
criteria.setFirstResult(num++);
criteria.setMaxResults(1);
return (MyEntity) criteria.uniqueResult();
}
};
}
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
SQL
drop table ENTITY if exists
create table ENTITY (id bigint generated by default as identity (start with 1), name varchar(255), primary key (id))
insert into ENTITY (name) values ('Entity1')
insert into ENTITY (name) values ('Entity2')
insert into ENTITY (name) values ('Entity3')
Unit test
package org.foo.bar;
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 static org.junit.Assert.assertEquals;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:applicationContext.xml"
})
public class MyEntityDaoTest {
#Autowired
private MyEntityDao dao;
#Test
public void testDao() throws Exception {
int count = 0;
for(MyEntity a : dao) {
count++;
}
assertEquals(3, count);
}
}
Here is my pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>org.foo.bar</groupId>
<artifactId>spring-aspectj-hibernate</artifactId>
<version>1.0</version>
<properties>
<spring.version>3.1.1.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.1.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
After all you have to run JVM with the following argument -javaagent:<PATH-TO>/spring-instrument-{vertion}.jar. To prevent adding -javaagent argument you can also configure aspectj compile-time weaving.
Related
Hi I try to add data to oraclexe database with spring mvc and hibernate by dao design pattern but it make this error
"org.springframework.web.util.NestedServletException"
how can solve this problem ?
This program just worked with springMVC whithout hibernate but when I try to add hibernate it doesn't work and give me the error I don't know how can connect springMVC with hibernate
this is my pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
</dependencies>
and class Resource.java
package com.spring.mvc.model;
import javax.persistence.*;
#Entity
#Table(name = "RESOURCSE")
public class Resource {
#Id
#GeneratedValue
#Column(name = "ID",unique = true,length = 10)
private int id;
#Column(name = "NAME", length = 25)
private String name;
#Column(name = "TYPE", length = 30)
private String type;
#Column(name = "unitOfMesure", length = 25)
private String unitOfMesure;
#Column(name = "notes", length = 25)
private String notes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Resource(String name, String type, String unitOfMesure, String notes) {
this.name = name;
this.type = type;
this.unitOfMesure = unitOfMesure;
this.notes = notes;
}
public String getUnitOfMesure() {
return unitOfMesure;
}
public void setUnitOfMesure(String unitOfMesure) {
this.unitOfMesure = unitOfMesure;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Resource() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Resource{" +
"id=" + id +
", name='" + name + '\'' +
", type='" + type + '\'' +
", unitOfMesure='" + unitOfMesure + '\'' +
", notes='" + notes + '\'' +
'}';
}
}
and ResourceDaoImpl
package com.spring.mvc.dao;
import com.spring.mvc.model.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository
#Transactional
public class ResourceDaoImpl implements ResourceDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addResource(Resource resource) {
try (Session session = this.sessionFactory.getCurrentSession()) {
session.persist(resource);
}
}
#Override
public void updateResource(Resource resource) {
Session session = this.sessionFactory.getCurrentSession();
session.update(resource);
}
#Override
public List<Resource> listResource() {
Session session = this.sessionFactory.getCurrentSession();
List list_resources = session.createQuery("from Resource ").list();
return list_resources;
}
#Override
public Resource getResourceById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Resource resourceId = session.load(Resource.class, id);
return resourceId;
}
#Override
public void removeResource(int id) {
Session session = this.sessionFactory.getCurrentSession();
Resource resourceId = session.load(Resource.class, id);
if (resourceId != null){
session.delete(resourceId);
}
}
}
and ResourceServiceImpl
package com.spring.mvc.service;
import com.spring.mvc.dao.ResourceDao;
import com.spring.mvc.model.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class ResourceServiceImpl implements ResourceService {
private ResourceDao resourceDao;
public ResourceDao getResourceDao() {
return resourceDao;
}
public void setResourceDao(ResourceDao resourceDao) {
this.resourceDao = resourceDao;
}
#Override
public void addResource(Resource resource) {
this.resourceDao.addResource(resource);
}
#Override
public void updateResource(Resource resource) {
this.resourceDao.updateResource(resource);
}
#Override
public List<Resource> listResource() {
return this.resourceDao.listResource();
}
#Override
public Resource getResourceById(int id) {
return this.resourceDao.getResourceById(id);
}
#Override
public void removeResource(int id) {
this.resourceDao.removeResource(id);
}
}
and ResourceController
package com.spring.mvc.controller;
import com.spring.mvc.model.Resource;
import com.spring.mvc.service.ResourceService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
#Controller
#RequestMapping("/resource")
public class ResourceController {
private ResourceService resourceService;
public void setResourceService(ResourceService resourceService) {
this.resourceService = resourceService;
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(Model model){
return "resource_add";
}
#ModelAttribute("resource")
public Resource resource(){
return new Resource();
}
#ModelAttribute("typeOptions")
public List<String> getTypes(){
return new LinkedList<>(Arrays.asList(new String[]{
"English","France","Italy"
}));
}
#ModelAttribute("radioOptions")
public List<String> getRadios(){
return new LinkedList<>(Arrays.asList(new String[]{
"Hour","Piece","Tones"
}));
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#ModelAttribute Resource resource){
this.resourceService.addResource(resource);
System.out.println(resource);
return "resource_add";
}
}
and this is my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/xsd/hibernate-configuration">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="connection.username">username</property>
<property name="connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property>
<mapping class="com.spring.mvc.model.Resource"></mapping>
</session-factory>
</hibernate-configuration>
First do not put #Transactional in front of DAO classes, put it only above the Services
classes.it won't be an error but it is a good practice
Edit
you did not add the hibernate in your spring-mvc, that's why #Autowired was not worked. you need to add hibernate config inside the spring like this (this is an example code, and change your appropriate values)
<!-- Add support for component scanning -->
<context:component-scan base-package="net.javaguides.springmvc" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Define Spring MVC view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC" />
<property name="user" value="user" />
<property name="password" value="password" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="net.javaguides.springmvc.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js, etc ... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
/********************************************************************/
in this method
#Override
public void updateResource(Resource resource) {
Session session = this.sessionFactory.getCurrentSession();
session.update(resource);
}
use beginTransaction and commit, like this
#Override
public void updateResource(Resource resource) {
Session session = this.sessionFactory.getCurrentSession();
session.beginTransaction();
session.update(resource);
session.getTransaction().commit();
}
and I am not sure you initialize the sessionFactory here
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
you can simply initialize using #Autowired annotation. like that,
#Autowired
protected SessionFactory sessionFactory;
Hi I have started to use Spring and JPA for the first time, I've tried many tutorials and questions here at stack overflow.But no success so I hope some one can give me a clear way out of this problem. I'm developing a toy application to get confident with the technology before I start the real project, I'm using Java, Spring, Hibernate, JPA and MySQL on a Maven-non web module project using java annotations as much as possible and as little xml as possible, I've found many web base application full of xml files but was unable to understand how to correct my project. The only thing I am able to understand is that I need to declare a persistence unit somehow telling the entity manager what to do, but there is no META-INF folder in my project (should create one?) AND most persistance.xml files I've found declare little more than what I have in my jpa-handler-conf.xml which seems to otherwise work fine.
So here are the project components:
The Beans:
package hp.esercizi.beans;
imports omitted...
#Component
#Entity
#Table(name = "AUTORE")
public class Autore {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name = "NOME", length = 20)
private String nome;
#Column(name = "COGNOME", length = 20)
private String cognome;
#OneToMany(targetEntity=Autore.class, mappedBy="amici")
private List<Autore> amici;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Autore> getAmici() {
return amici;
}
public void setAmici(List<Autore> amici) {
this.amici = amici;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
}
package hp.esercizi.beans;
imports omitted...
#Component
#Entity
#Table(name = "MESSAGGIO")
public class Messaggio {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name = "TESTO", nullable = false, length = 200)
private String testo;
#ManyToOne
#JoinColumn(name="AUTORE_ID")
private Autore autore;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public Autore getAutore() {
return autore;
}
public void setAutore(Autore autore) {
this.autore = autore;
}
}
The DAOs:
package hp.esercizi.dao;
imports omitted...
public interface AutoreDAO {
public EntityManager getEntityManager();
public void setEntityManager(EntityManager entityManager);
public void insert(Autore autore);
public List<Autore> selectAll();
public Autore findAutoreByID(Long id);
}
package hp.esercizi.dao;
imports omitted...
#Repository("AutoreDAO")
#Transactional
public class AutoreDAOJPA2Impl implements AutoreDAO {
private static final String SELECT_QUERY = "select a from autore a";
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void insert(Autore autore) {
entityManager.persist(autore);
}
public List<Autore> selectAll() {
Query query = (Query) entityManager.createQuery(SELECT_QUERY);
List<Autore> autori = (List<Autore>) query.getResultList();
return autori;
}
public Autore findAutoreByID(Long id) {
return entityManager.find(Autore.class, id);
}
}
package hp.esercizi.dao;
imports omitted...
public interface MessaggioDAO {
public EntityManager getEntityManager();
public void setEntityManager(EntityManager entityManager);
public void insert(Messaggio messaggio);
public List<Messaggio> selectAll();
}
package hp.esercizi.dao;
imports omitted...
#Repository("MessaggioDAO")
#Transactional
public class MessaggioDAOJPA2Impl implements MessaggioDAO {
private static final String SELECT_QUERY = "select m from messaggio m";
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void insert(Messaggio messaggio) {
entityManager.persist(messaggio);
}
public List<Messaggio> selectAll() {
Query query = (Query) entityManager.createQuery(SELECT_QUERY);
List<Messaggio> messaggi = (List<Messaggio>) query.getResultList();
return messaggi;
}
}
Entity Manager and Data Source configuration XML (jpa-handler-conf.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: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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="vendorAdaptor" />
<property name="packagesToScan" value="hp.esercizi" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="abstractVendorAdaptor" abstract="true">
<!-- <property name="generateDdl" value="${db.generate}" /> -->
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
<bean id="vendorAdaptor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
parent="abstractVendorAdaptor">
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/DB_SpringContext" />
<property name="username" value="root" />
<property name="password" value="Lavoro01" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
The context configuration:
package hp.esercizi.utility;
imports omitted...
#ComponentScan("hp.esercizi.beans")
public class BeansConfig {
}
package hp.esercizi.utility;
imports omitted...
#Configuration
#ComponentScan("hp.esercizi.dao")
public class DataSourceConfig {
}
package hp.esercizi.utility;
imports omitted...
#Configuration
#Import({BeansConfig.class , DataSourceConfig.class})
#ImportResource("jpa-handler-conf.xml")
public class SpringConfig {
}
The Main:
package hp.esercizi.main;
imports omitted...
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("AutoreDAO");
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
Messaggio msg = (Messaggio) context.getBean("messaggio");
entitymanager.merge(msg);
Autore aut = (Autore) context.getBean("autore");
entitymanager.merge(aut);
msg.setTesto("Ciao Mondo!!!");
aut.setNome("Mario");
aut.setCognome("Rossi");
System.out.println(msg.getTesto());
System.out.println(msg.getAutore().getNome() + " " + msg.getAutore().getCognome());
entitymanager.persist(msg);
entitymanager.getTransaction().commit();
Messaggio msg2 = entitymanager.find(Messaggio.class, 1);
ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(mapper.writeValueAsString(msg2));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entitymanager.close( );
emfactory.close( );
}
}
The 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>esercizi</groupId>
<artifactId>SpringContext</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.0.CR2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.0.CR2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>
</project>
I am new to Spring so as to Hibernate frameworks. The task is to create a project with both front and back ends, but for now I would like to focus on DB connection.
I have MySQL database on localhost within my MySQL server. There is a simple application which needs to create clients, orders and search for them in the DB, so the task is trivial. Yet, I encounter the following ecxeption:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory ee.st.running.dao.ClientDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="ee.st.running.model.Client"/>
I tried some manipulations, read many similar issues here, which led me to other exceptions much like this.
My config.xml file is:
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package=".*" />
<tx:annotation-driven/>
<context:annotation-config />
<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/sqlconnection" />
<property name="username" value="admin" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.dao.ClientDAOImpl</value>
<value>ee.st.running.model.Order</value>
<value>ee.st.running.dao.OrderDAOImpl</value>
</list>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
<bean id = "client" class = "ee.st.running.model.Client">
<property name="clientDAO" ref = "ClientDAO"></property>
</bean>
<bean id = "clientDAO" class = "ee.st.running.dao.ClientDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
<bean id = "order" class = "ee.st.running.model.Order">
<property name="orderDAO" ref = "OrderDAO"></property>
</bean>
<bean id = "orderDAO" class = "ee.st.running.dao.OrderDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
</beans>
And here is the project structure:
And here is 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">
<modelVersion>4.0.0</modelVersion>
<groupId>ee.st.running.aktorstask</groupId>
<artifactId>aktorstask</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
</properties>
</project>
And the classes:
Client
package ee.st.running.model;
//import java.util.List;
//import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
//import javax.persistence.OneToMany;
import javax.persistence.Table;
import ee.st.running.dao.ClientDAOInterface;
import ee.st.running.dao.ClientDAOImpl;
#Entity
#Table(name = "client")
public class Client implements ClientInterface {
private Order o;
ClientDAOInterface ClientDAOInterface;
#Id
#GeneratedValue
private int id;
#Column (name = "name")
private String name;
#Column (name = "surename")
private String surename;
#Column (name = "address")
private String address;
#Column (name = "phone_number")
private long phoneNumber;
#Column (name = "id_code")
private long idCode;
//#OneToMany(mappedBy = «client», fetch = FetchType.LAZY)
public void makeorder() {
o.newOrder();
}
// getters nd setters
public Order getO() {
return o;
}
public void setO(Order o) {
this.o = o;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurename() {
return surename;
}
public void setSurename(String surename) {
this.surename = surename;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public long getIdCode() {
return idCode;
}
public void setIdCode(int idCode) {
this.idCode = idCode;
}
// ctor
public Client ()
{
}
public void setClientInfDAO (ClientDAOInterface ClientDAOInterface)
{
this.ClientDAOInterface = ClientDAOInterface;
}
public void save(Client client) {
ClientDAOInterface.save(client);
}
public void update(Client client) {
ClientDAOInterface.update(client);
}
public void remove(Client client) {
ClientDAOInterface.remove(client);
}
}
ClientInterface:
package ee.st.running.model;
public interface ClientInterface {
public void makeorder ();
public void save(Client client);
public void update (Client client);
public void remove (Client client);
}
ClientDAOInterface:
package ee.st.running.dao;
import java.util.List;
import ee.st.running.model.Client;
public interface ClientDAOInterface {
public void removeClient (long id);
public List<Client> listClient();
public void save (Client client);
public void update (Client client);
public void remove (Client client);
}
ClientDAOImpl:
package ee.st.running.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import ee.st.running.model.Client;
#Repository
public class ClientDAOImpl extends HibernateDaoSupport implements ClientDAOInterface {
#Autowired
private SessionFactory sessionFactory;
public void AddClient(Client client) {
sessionFactory.getCurrentSession().save(client);
}
public void removeClient(long id) {
Client client = (Client) sessionFactory.getCurrentSession().load(Client.class, id);
if (null != client) {
sessionFactory.getCurrentSession().delete(client);
}
}
#SuppressWarnings("unchecked")
public List<Client> listClient() {
return sessionFactory.getCurrentSession().createQuery("from Client").list();
}
public void save(Client client) {
sessionFactory.getCurrentSession().save(client);
}
public void update(Client client) {
// TODO Auto-generated method stub
}
public void remove(Client client) {
// TODO Auto-generated method stub
}
}
And lastly my hibernate.cfg:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="ee.st.running.model.Client" />
<mapping class="ee.st.running.model.Order" />
</session-factory>
</hibernate-configuration>
I modified it several times, adding some additional info. What I currently want is to check, whether it works, so in the Main class I wrote primitive code to store info to database and see whether it actually stored, so I could move on:
package ee.st.running.aktorstask;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ee.st.running.dao.*;
import ee.st.running.model.*;
public class Main {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext ("./config.xml");
Client clientx = (Client) appContext.getBean("client");
Client client = new Client ();
client.setName("Vasilij");
client.setIdCode(389844455);
client.setAddress("Pae 485 54 Tartu");
client.setSurename("B");
//client.makeorder();
clientx.save(client);
}
}
It now gives me mappingexception
Any ideas, why? And, by the way who is "AnnotationConfiguration instance" and where it supposed to be?
Normal hibernate.cfg.xml uses Configuration class for building Sessionfactory object
return new Configuration().configure().buildSessionFactory();
You need to use AnnotationConfiguration for the same.
In your above example you have specified classes in sessionFactory bean as
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.dao.ClientDAOImpl</value>
<value>ee.st.running.model.Order</value>
<value>ee.st.running.dao.OrderDAOImpl</value>
</list>
</property>
Wrong thing you did here is you added DAO classes also. AnnotatedClasses should be domain classes.
You can remove them and keep only Client and Order in that.
Secondly you have also provided hibernate.cfg.xml file. Hence you can remove that as you are using annotated classes.
Hence final code may look like this:
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.model.Order</value>
</list>
</property>
And removing hibernate.cfg.xml
This error is killing me, i searched a lot of similar topics here, but none of them helped me!
So, i'm using spring MVC+hibernate. Please, just take a look, maybe you will find mistake which i missed!
Here is my files:
Clients
package app.model;
import javax.persistence.*;
#Entity
#Table(name = "clients")
public class Clients {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int client_id;
private String gender;
private String first_name;
private String last_name;
private String country;
private String city;
private String birthdate;
private String phone;
private String email;
private int orders;
private double total_income;
public Clients() {
}
public Clients(int client_id, String gender, String first_name,
String last_name, String country, String city, String birthdate,
String phone, String email, int orders, double total_income) {
super();
this.client_id = client_id;
this.gender = gender;
this.first_name = first_name;
this.last_name = last_name;
this.country = country;
this.city = city;
this.birthdate = birthdate;
this.phone = phone;
this.email = email;
this.orders = orders;
this.total_income = total_income;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public int getClient_id() {
return client_id;
}
public void setClient_id(int client_id) {
this.client_id = client_id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getOrders() {
return orders;
}
public void setOrders(int orders) {
this.orders = orders;
}
public double getTotal_income() {
return total_income;
}
public void setTotal_income(double total_income) {
this.total_income = total_income;
}
}
ClientsService
package app.service;
import java.text.ParseException;
import java.util.List;
import app.model.Clients;
public interface ClientsService {
public void addClient(Clients client);
public void updateClient(Clients client) throws ParseException;
public void deleteClient(Clients client) throws ParseException;
public Clients getClient(int client_id);
public List<Clients> getAllClients();
}
ClientsServiceImpl
package app.service.impl;
import java.text.ParseException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import app.dao.ClientsDao;
import app.model.Clients;
import app.service.ClientsService;
#Service
public class ClientsServiceImpl implements ClientsService {
#Autowired
private ClientsDao clientsDao;
public ClientsServiceImpl() {
}
public List<Clients> getAllClientsList() {
return clientsDao.getAllClients();
}
#Transactional
public void addClient(Clients client) {
clientsDao.addClient(client);
}
#Transactional
public void updateClient(Clients client) throws ParseException{
clientsDao.updateClient(client);
}
#Transactional
public void deleteClient(Clients client) throws ParseException{
clientsDao.deleteClient(client);
}
#Transactional
public Clients getClient(int client_id) {
return clientsDao.getClient(client_id);
}
#Transactional
public List<Clients> getAllClients() {
return clientsDao.getAllClients();
}
}
ClientsDao
package app.dao;
import java.text.ParseException;
import java.util.List;
import app.model.Clients;
public interface ClientsDao {
public void addClient(Clients client);
public void updateClient(Clients client) throws ParseException;
public void deleteClient(Clients client) throws ParseException;
public Clients getClient(int client_id);
public List<Clients> getAllClients();
}
ClientsDaoImpl
package app.dao.impl;
import java.text.ParseException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import app.model.Clients;
import app.dao.ClientsDao;
import app.logic.Similar;
#Repository
public class ClientsDaoImpl implements ClientsDao {
#Autowired
public SessionFactory session;
public ClientsDaoImpl() {
}
#Transactional
#SuppressWarnings("unchecked")
public List<Clients> getAllClients() {
return session.getCurrentSession().createQuery("from Clients").list();
}
#Transactional
public void addClient(Clients client) { // add new client
session.getCurrentSession().save(client);
}
#Transactional
public void updateClient(Clients client) throws ParseException { // update client
session.getCurrentSession().update(client);
}
#Transactional
public void deleteClient(Clients client) throws ParseException { // delete client if he\she doesnt have any orders
session.getCurrentSession().delete(client);
}
#Transactional
public Clients getClient(int client_id) {
return (Clients)session.getCurrentSession().get(Clients.class, client_id);
}
}
ClientsController
package app.controller;
import java.text.ParseException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import app.model.Clients;
import app.service.ClientsService;
#Controller
public class ClientsController {
#Autowired
public ClientsService clientsService;
public ClientsController(){
}
#RequestMapping("/index")
public String setupForm(Map<String, Object> map) {
Clients client = new Clients();
map.put("client", client);
map.put("clientsList", clientsService.getAllClients());
return "client";
}
#RequestMapping(value = "/client.do", method = RequestMethod.POST)
public String doActions(#ModelAttribute Clients client,
BindingResult result, #RequestParam String action,
Map<String, Object> map) throws ParseException {
Clients clientResult = new Clients();
switch (action.toLowerCase()) {
case "add":
clientsService.addClient(client);
clientResult = client;
break;
case "edit":
clientsService.updateClient(client);
clientResult = client;
break;
case "delete":
clientsService.deleteClient(client);
clientResult = new Clients();
break;
case "search":
Clients searchedClient = clientsService.getClient(client.getClient_id());
clientResult = searchedClient != null ? searchedClient : new Clients();
break;
}
map.put("client", clientResult);
map.put("clientsList", clientsService.getAllClients());
return "client";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>ProjectMVC</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/projectdb
jdbc.username=root
jdbc.password=root
spring-servlet.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="app.*">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:spring-configured />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<tx:annotation-driven />
<aop:config proxy-target-class="true"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
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>Project</groupId>
<artifactId>Project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Hibernate resources -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>20030825.183949</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- Log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/main/test</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/webapp</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
upd: forgot hibernate.cfg
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="app.model.Clients" />
</session-factory>
</hibernate-configuration>
Possibly try this solution from here: Getting a org.springframework.beans.factory.BeanCreationException with my first Maven, Spring Project
just add:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${your-spring-version}</version>
</dependency>
I think your missing the repository name in your ClientsDaoImpl .
#Repository("clientsDAO")
public class ClientsDaoImpl implements ClientsDao.....
i am using netbeans 7.2, postgres sql,jpa2,hibernate 4.2.
i just created a new maven simple java project(not webapp).
However i have done setup hibernate and jpa,but autowire "wpService" get null(not sure is it caused by hibernate configuration).
here is my project file(innovax.rar), if you would like to test it.
https://skydrive.live.com/#cid=837EF1FA9A4C06AE&id=837EF1FA9A4C06AE%21130
my main class
package sg.com.innovax.Twitter;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sg.com.innovax.Twitter.DBObject.service.impl.wall_postServiceImpl;
import sg.com.innovax.Twitter.DBObject.service.wall_postService;
import twitter4j.*;
public final class twitter {
public static void main(String[] args) throws TwitterException {
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
test a = new test();
}
}
my test instance
import org.springframework.beans.factory.annotation.Autowired;
import sg.com.innovax.Twitter.DBObject.service.wall_postService;
/**
*
* #author Nimamakaho
*/
public class test {
#Autowired
private wall_postService wpService;
test(){
// wpService is null when i break point here
System.out.println("Asd");
}
}
my wall post object
package sg.com.innovax.Twitter.DBObject;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Formatter;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "wall_post")
#NamedQueries({
#NamedQuery(name="wall_post.findById", query="select wp from wall_post wp where wp.id = :id")
// #NamedQuery(name="wall_post.getByHashtagsRecords", query="select wp.*,case when wpa.id is null then false else true end as ack from (select wp from wall_post wp where wp.id in (:id) ) as wp LEFT JOIN wall_post_acknowledgement wpa on wp.id = wpa.wall_post_id")
})
public class wall_post {
#Id
#SequenceGenerator(name="wall_post_id_seq", sequenceName="wall_post_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="wall_post_id_seq")
#Basic(optional = false)
private int id;
private String title;
private String message;
private boolean enable_acknowledgement;
private boolean enable_comment;
private Timestamp created_time;
private Timestamp edited_time;
private Timestamp deleted_time;
private Timestamp last_updated;
public Timestamp getLast_updated() {
return last_updated;
}
public void setLast_updated(Timestamp last_updated) {
this.last_updated = last_updated;
}
private int user_id;
public boolean isEnable_comment() {
return enable_comment;
}
public void setEnable_comment(boolean enable_comment) {
this.enable_comment = enable_comment;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isEnable_acknowledgement() {
return enable_acknowledgement;
}
public void setEnable_acknowledgement(boolean enable_acknowledgement) {
this.enable_acknowledgement = enable_acknowledgement;
}
public Timestamp getCreated_time() {
return created_time;
}
public void setCreated_time(Timestamp created_time) {
this.created_time = created_time;
}
public Timestamp getEdited_time() {
return edited_time;
}
public void setEdited_time(Timestamp edited_time) {
this.edited_time = edited_time;
}
public Timestamp getDeleted_time() {
return deleted_time;
}
public void setDeleted_time(Timestamp deleted_time) {
this.deleted_time = deleted_time;
}
}
my wall post service
package sg.com.innovax.Twitter.DBObject.service;
import java.util.List;
import sg.com.innovax.Twitter.DBObject.*;
public interface wall_postService {
public wall_post findById(Integer id);
public boolean isAuthorizeToAccess(int wallPostID,int userid);
}
my wall post service impl
package sg.com.innovax.Twitter.DBObject.service.impl;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.SQLQuery;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.cfg.Configuration;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import sg.com.innovax.Twitter.DBObject.*;
import sg.com.innovax.Twitter.DBObject.service.wall_postService;
#Service
#Repository
public class wall_postServiceImpl implements wall_postService {
private static final Logger logger = LoggerFactory.getLogger(wall_postServiceImpl.class);
#PersistenceContext
private EntityManager em;
private EntityManagerFactory emf;
#Override
public wall_post findById(Integer id) {
try{
if(id == null) return null;
TypedQuery<wall_post> query = em.createNamedQuery("wall_post.findById", wall_post.class);
query.setParameter("id", id);
return query.getSingleResult();
}catch(NoResultException ex)
{
return null;
}
catch(Exception ex)
{
logger.error("=================================================");
logger.error("findById()",ex);
return null;
}
}
public boolean isAuthorizeToAccess(int wallPostID,int userid) {
try
{
String sql =
" select wall_post_id from wall_post_authority where group_id in "+
" (select group_id from group_user where user_id = :userid group by group_id) "+
" and wall_post_id = :wallPostID group by wall_post_id ";
Query query = em.createNativeQuery(sql).setParameter("userid", userid).setParameter("wallPostID", wallPostID);
Object a = query.getSingleResult();
return true;
}catch(NoResultException ex)
{
return false;
}
catch(Exception ex)
{
logger.error("=================================================");
logger.error("isAuthorizeToAccess()",ex);
return false;
}
}
}
my application context 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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/testspring" />
<property name="username" value="postgres" />
<property name="password" value="admin" />
</bean>
<!-- Database
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="admin" />
</bean>
-->
<!-- Entity Manager -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
</bean>
</property>
<property name="packagesToScan" value="sg.com.innovax" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Jpa Repositories -->
<jpa:repositories base-package="sg.com.innovax.Twitter"></jpa:repositories>
</beans>
here is my pom file
<?xml version="1.0" encoding="UTF-8"?>
<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>sg.com.innovax</groupId>
<artifactId>innovax</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<org.springframework-version>3.2.3.RELEASE</org.springframework-version>
<org.springjpa-version>1.3.2.RELEASE</org.springjpa-version>
</properties>
<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.9.Final</version>
</dependency>
<!-- Additional Analyzers: -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-analyzers</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!-- Infinispan integration: -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-infinispan</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.170</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springjpa-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
AFAIK you cannot autowire a static field. Try it as an instance member and see if that solves your problem.
try to create a setter method for ur private field , and place the autowire annotation on the method like this:
private wall_postService wpService;
#Autowired
public void setwpService(wall_postService wpService){
this.wpService = wpService ;
}
and now use the method in the test class ...