I have a problem with autowiring component with spring. Im trying inject bean (UserRepository) into java class Reader. When im using autowire annotation the object is allways null. I try add into spring-config.xml bean 'reader' whith property 'userRepository' but this not working too. What is missing?
spring-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="reader" />
<context:annotation-config/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.sqlite.JDBC"/>
<property name="url" value="jdbc:sqlite:C:/Users/Piotr/Downloads/projekt na projekt/IntelliDOM/IntelliDOM.sqlite"/>
<property name="username" value=""/>
<property name="password" value=""/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="userRepository" class="repository.UserRepositoryHibernate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Reader.java:
#Service
#Path("/")
public class Reader {
#Autowired
private UserRepository userRepository;
#GET
#Path("/test")
public void test(){
System.out.println("test");
userRepository.findAll(); //this is allways null
}
#POST
#Path("/dom2")
public Response read(String nonParsedWords){
Words parsedWords = WordParser.parseWords(nonParsedWords);
for(String word : parsedWords.getWords()){
System.out.println(word);
}
return Response.status(200).entity(nonParsedWords).build();
}
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Is there something wrong with context of application? Why this bean cant not be injected?
Spring version: 2.5.6
EDIT:
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="connection.url">jdbc:sqlite:IntelliDOM.sqlite</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="entity.User"/>
</session-factory>
</hibernate-configuration>
Related
I've got a problem with my Spring web application with JPA and Glassfish server. When I'm trying to add new entry to a database (entityManager.persist()), I receive:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
Here's my code:
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="LibraryPU">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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: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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<context:component-scan base-package="service, controller, dao" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="LibraryPU" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />
<property name="url" value="jdbc:derby://localhost:1527/Library" />
<property name="username" value="app" />
<property name="password" value="app" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
UserDao.java
package dao;
import entity.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository("userDao")
#Transactional
public class UserDao {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void insert(User user) {
entityManager.persist(user);
entityManager.flush();
}
}
Thanks in advance!
if You want to use JTA transaction in your code then
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
remove the JpaTransactionManager and replace it with a JTA transaction manager.
Also define the transacation-type="JTA" like
<persistence-unit name="LibraryPU" transaction-type="JTA">
in persistence.xml.
I am trying to do Spring 4 + Hibernate 4 configuration. But I am facing sessionFactory = null in the Controller. Below are the configurations and code.
What is the mistake in this configuration?
spring-database.xml
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- MySQL data source -->
<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/personal" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>/orm/Song.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean id="songDao" class="com.letsdo.impl.SongImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- MUST have transaction manager, using aop and aspects -->
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
orm/Song/hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.letsdo.model.Song" table="song" catalog="personal">
<id name="id" type="int">
<column name="id" length="45" />
<generator class="increment"/>
</id>
<property name="filePath" column="filepath"/>
<property name="fileName" column="filename"/>
<property name="album" column="album"/>
<property name="title" column="title"/>
<property name="size" column="size"/>
</class>
</hibernate-mapping>
SongDao.java
public interface SongDao {
public List<String> getAllAlbums();
}
SongImpl.java
#Service
#Transactional
public class SongImpl implements SongDao{
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<String> getAllAlbums(){
List<String> allAlbums = new ArrayList<String>();
Query query = getSessionFactory().getCurrentSession().createQuery("Select DISTINCT Album from song");
allAlbums = query.list();
return allAlbums;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Controller: HomeController.java
public class HomeController {
#Autowired private SongImpl songDao;
#RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView welcomePageBeforeLogin(HttpServletRequest request, HttpServletResponse response,HttpSession session){
ModelAndView model = new ModelAndView();
List<String> album = songDao.getAllAlbums();
model.addObject("albumsize",album.size());
model.setViewName("hello");
return model;
}
}
I think you are ending up with two beans of class SongImpl - one that is defined in xml (named songDao), and another one annotated with #Service (named by default songImpl). The latter one has no SessionFactory autowired, that's why it is null.
You can find more info about it in one of the answers here.
If component scanning is enabled, spring will try to create a bean
even though a bean of that class has already been defined in the
spring config xml. However if the bean defined in the spring config
file and the auto-discovered bean have the same name, spring will not
create a new bean while it does component scanning.
The solution is to remove the xml version of the bean (if you don't need it), and to autowire SessionFactory in SongImpl.
An exception occurs while I'm trying to persist an object.
import org.springframework.transaction.annotation.Transactional;
#Repository("DBRepository")
#Transactional
public class DBRepository implements Repository {
#PersistenceContext
private EntityManager entityManager;
#Override
public void addElement(Element element) {
logger.debug("Element {} is going to be added to database", element);
entityManager.persist(element);
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="p_unit" transaction-type="RESOURCE_LOCAL"/>
</persistence>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/jpa-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
jpa-config.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"
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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Using annotation to configure application -->
<context:annotation-config/>
<context:component-scan base-package="web.tmh"/>
<!-- Tells Spring to use persistence context annotation -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<tx:annotation-driven mode="proxy" transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="p_unit"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<entry key="hibernate.hbm2ddl.auto" value="update"/>
</map>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- autoReconnect=true param allows our application to reconnect to base if connection was lost -->
<property name="url" value="jdbc:mysql://localhost:3306/TellMeHow?autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
</beans>
So as you can see I used right Transactional annotation, and have <tx:annotation-driven mode="proxy" transaction-manager="transactionManager"/>in my jpa-config.xml. So I don't really understand why it doesn't want do work
Ok, the problem was solved. I've made a small mistake in my dispatcher-config.xml:
So instead of
<mvc:annotation-driven/>
<context:component-scan base-package="web.tmh"/>
I had to write
<mvc:annotation-driven/>
<context:component-scan base-package="web.tmh.controller"/>
I thought that component-scan worked recursively, but seems like it didn't...
I am a newbie to Spring and trying to integrate Spring and Hibernate. But I am facing nullpointer in SessionFactory.
Error Description:
java.lang.NullPointerException
com.ume.dao.UserDaoImpl.openSession(UserDaoImpl.java:29)
com.ume.dao.UserDaoImpl.getUser(UserDaoImpl.java:34)
com.ume.LoginController.getUserCredentials(LoginController.java:39)
Another Error Description
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544)
com.ume.dao.UserDaoImpl.openSession(UserDaoImpl.java:31)
com.ume.dao.UserDaoImpl.getUser(UserDaoImpl.java:37)
com.ume.service.UserServiceImpl.getUser(UserServiceImpl.java:23)
My dispatchar-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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.nptest" />
<mvc:annotation-driven />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<property name="basename" value="messages" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.nptest.pojo.UserPojo</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My DAOImplementation class
#Repository
public class UserDaoImpl implements UserDao{
#Autowired
private SessionFactory sessionFactory;
private Session openSession()
{
return sessionFactory.getCurrentSession();
}
public UserPojo getUser(String username, String password)
{
List<UserPojo> userlist=new ArrayList<UserPojo>();
Query query=openSession().createQuery("from UserPojo u WHERE u.login=:username AND u.userpwd=:password");
query.setParameter("login",username);
query.setParameter("password",password);
System.out.println("MADAN Query "+ query);
userlist=query.list();
if(userlist.size()>0)
return userlist.get(0);
else return null;
}
}
My Service Interface
public interface UserService {
public UserPojo getUser(String username,String password);
}
My Service Implementation class
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Transactional
public UserPojo getUser(String username, String password) {
return userDao.getUser(username, password);
}
My controller class from where I make these call, I have instantiated the Service class by this
#Autowired
private UserService userservice;
And in the method I called
UserPojo user=userservice.getUser(username, password);
looks like you have instantiated a UserDaoImpl manually, the sessionFactory didn't get wired, please post the code how you use UserDaoImpl
add annotation to UserDaoImpl and put it under package com.nptest
package com.nptest.dao;
#Repository public class UserDaoImpl implements UserDao
then autowired UserDaoImpl in your app
--edit--
to enable annotation based transcation, you have to add
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
in the application context xml
My goal is to instanciate the EntityManagerFactory from applicationContext.xml file to get all posts registered in SQL database.
Here's the content of the main files :
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<!-- Properties files linkers -->
<context:property-placeholder location="/WEB-INF/resources/database/jdbc.properties"/>
<context:property-placeholder location="/WEB-INF/resources/database/hibernate.properties"/>
<!-- Config database - initialization -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Three main layers definition -->
<context:annotation-config />
<context:component-scan base-package="com.zone42"/>
<!-- Transaction sub-system initialization -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
(WEB-INF/classes/)persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="post-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.zone42.model.Post</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>
PostDAO.java
public class PostDAO extends GenericDAOEntity<Post> implements IPostDAO
{
}
GenericDAOEntity.java
#Transactional
public class GenericDAOEntity<T> implements IGenericDAO<T>
{
/**
* Properties
*/
#Autowired
#PersistenceContext(unitName="post-unit")
private EntityManagerFactory entityManagerFactory/* = Persistence.createEntityManagerFactory(persistence_unit_name)*/;
//Get all posts
#SuppressWarnings("unchecked")
public List<T> findAll(Class<T> obj) {
EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Query query = entityManager.createQuery("from " + obj.getSimpleName());
return (query.getResultList());
}
/**
* Accessors
*/
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
#PersistenceContext(unitName="post-unit")
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
}
I tried several config combinations but without success. The NullPointerException comes from the findAll method when I want to create an instance of EntityManager from the entityfactory instance. I think I have a configuration problem. I want to precise that the code works whn I instanciate the EntityManagerFactory using operator new directly in the class. Now I just want to allocate my factory choosing another way, the one using xml from appicationContext.xml file. Can anyone help me? Thanks in advance.
You need to either mark the field/setter as #Autowired or explicitly wire the reference up in your XML:
<bean class="PostDAO">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>