How to access SessionFactory from spring-dispatcher-servlet.xml to DAO - java

I am creating a spring web application with help of hibernate. I have created spring-dipatcher-servlet.xml for all the configuration. I want to access the database using hibernate without creating the hibernate.cfg.xml file as I am using spring. I am getting Null Pointer Exception while accessing the Session Factory in DAO.
Following are the snippets of what I have done till now.
----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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>quiz_mcq</display-name>
<welcome-file-list>
<welcome-file>welcome.htm</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
---spring-dispatcher-servlet---
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.quiz_mcq.controller" />
<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/quiz_mcq" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="com.quiz_mcq.bean"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
---controller ---
#Controller
public class QuizMcqController {
UserService userService;
#RequestMapping(value="/welcome.htm")
public ModelAndView redirectToLoginPage(){
ModelAndView modelAndView = new ModelAndView("login");
return modelAndView;
}
#RequestMapping(value="/AuthenticateUser.htm", method = RequestMethod.POST)
public ModelAndView authenticateUser(#RequestParam("username") String username, #RequestParam("password")String password){
userService = new UserService();
boolean flag = userService.authenticate(username,password);
if(flag){
ModelAndView modelAndView = new ModelAndView("login");
return modelAndView;
}
else{
ModelAndView modelAndView = new ModelAndView("wrong");
return modelAndView;
}
}
}
--- Service ---
public class UserService {
User user;
UserDao dao;
public boolean authenticate(String username, String password) {
user = new User();
user.setUsername(username);
user.setPassword(password.toCharArray());
if(dao.authenticateUser(user))
{
return true;
}
return false;
}
}
---DAO ---
#Repository
public class UserDao implements IUser {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public boolean authenticateUser(User user) {
String username = user.getUsername();
char[] password = user.getPassword();
System.out.println(username +" <----> "+password);
String hql = "from User where username='username' and password ='password'";
Query query = getSessionFactory().openSession().createQuery(hql);
List list = new ArrayList();
list = query.list();
if (list.size() > 0 && list != null) {
return true;
}
return false;
}
}
How can I resolve my issue, what I am doing wrong?
Thanks in advance. Your help is appreciated.

here the problem is currently your dispatcher servlet does not know how to create and set the bean SessionFactory from. (As you see, your setSessionFactory is in UserDao class )
you may need to declare UserDao bean in spring-dispatcher-servlet.xml.
for eg:
<bean id="userDAO" class="your.package.nameforUserDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

Related

Spring - URI mapping issue [duplicate]

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
I´m getting a mapping error on my application, any help would be greatly appreciated! =)
Error message: No mapping found for HTTP request with URI [/springapp/priceincrease.htm] in DispatcherServlet with name 'springapp'
You can find some code below:
PriceIncreaseFormController.java
#Controller
#RequestMapping(value="/priceincrease.htm")
public class PriceIncreaseFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private ProductManager productManager;
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#Valid PriceIncrease priceIncrease, BindingResult result)
{
if (result.hasErrors()) {
return "priceincrease";
}
int increase = priceIncrease.getPercentage();
logger.info("Increasing prices by " + increase + "%.");
productManager.increasePrice(increase);
return "redirect:/hello.htm";
}
#RequestMapping(method = RequestMethod.GET)
protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
return priceIncrease;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
public ProductManager getProductManager() {
return productManager;
}
}
app-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="productManager" class="com.companyname.springapp.service.SimpleProductManager">
<property name="products">
<list>
<ref bean="product1"/>
<ref bean="product2"/>
<ref bean="product3"/>
</list>
</property>
</bean>
<bean id="product1" class="com.companyname.springapp.domain.Product">
<property name="description" value="Lamp"/>
<property name="price" value="5.75"/>
</bean>
<bean id="product2" class="com.companyname.springapp.domain.Product">
<property name="description" value="Table"/>
<property name="price" value="75.25"/>
</bean>
<bean id="product3" class="com.companyname.springapp.domain.Product">
<property name="description" value="Chair"/>
<property name="price" value="22.79"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.companyname.springapp.web" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
web.xml
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Springapp</display-name>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/app-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
You forgot to add handler mapping in your application context:
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
There problem in your GET method : formBackingObject.
Depends upon your requirement it should return to view or make it REST method.
Case 1 : return to view (JSP,HTML,XSLT...)
#RequestMapping(value="/priceincrease.htm",method = RequestMethod.GET)
protected String formBackingObject(HttpServletRequest request,Model model) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
model.addAttribute("priceIncrease",priceIncrease);
return "view_name";
}
Case 2 : REST method using #ResponseBody (jackson.core Jar is necessary)
#RequestMapping(value="/priceincrease.htm",method = RequestMethod.GET)
#ResponseBody
protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
return priceIncrease;
}
Here you have modify controller's parent mapping (simply remove it) for both cases
#Controller
public class PriceIncreaseFormController {
}

WebSphere no persistent classes found for query class

I'm new to WebSphere and am trying to host a simple website that I can log into using an Oracle database.
I can get to my website, but when I try and log in I get the following warning and am not able to log in:
[WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null.
[WARNING ] HHH000183: no persistent classes found for query class: select a FROM com.model.User a where username = 'user'
No entity found for query
The warning no persistent classes found for query class: is being thrown when I try and create the query to log in inside of my CommonServiceImple.java:
Query query = getEntityManager().createQuery("select a FROM " + className + " a where username = '" + username + "'");
The No entity found for query is caused in the next line trying to run the query. This is because the query object is null because of the previous warning: Object obj = query.getSingleResult();.
server.xml
<dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
<jdbcDriver id="oracle-driver" libraryRef="oracle-lib">
<library></library>
</jdbcDriver>
<connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
<properties.oracle URL="jdbc:oracle:thin:#crappie.ddvc.local:1521:STILOG" password="password" user="user"/>
</dataSource>
<library id="oracle-lib">
<fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
</library>
web.xml
<resource-ref>
<description>DataSource</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
<mapped-name>jdbc/test</mapped-name>
</resource-ref>
ibm-web-bnd.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-bnd
xmlns="http://websphere.ibm.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
version="1.0">
<virtual-host name="default_host" />
<resource-ref name="jdbc/test" binding-name="jdbc/test"/>
</web-bnd>
persistence.xml
<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_1_0.xsd"
version="1.0">
<persistence-unit name="pu1">
</persistence-unit>
</persistence>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="commonService" class="com.service.CommonServiceImpl"/>
<bean id="mainMenuService" class="com.service.MainMenuServiceImpl"/>
<bean id="storeFilterService" class="com.service.StoreFilterServiceImpl"/>
<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="ORACLE" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="persistenceUnitManager" ref="pum"/>
<property name="persistenceUnitName" value="pu1" />
<property name="jpaProperties">
<props>
<prop key="org.hibernate.envers.store_data_at_delete">true</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/test</value>
</property>
<property name="cache"
value="true"/>
<property name="lookupOnStartup"
value="true"/>
<property name="resourceRef"
value="true"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="pum"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="loginAction" scope="prototype" class="com.action.LoginAction">
<constructor-arg ref="commonService" />
</bean>
<bean id="userAction" scope="prototype" class="com.action.UserAction">
<constructor-arg ref="commonService" />
</bean>
</beans>
Nothing interesting in User.java
#Entity
#Table(name="WEB_PAGE_USERS")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="seq")
#SequenceGenerator(name="seq", sequenceName="WEB_PAGE_USERS_ID_SEQ")
private Integer id;
private String username;
private String password;
private String name;
//...
}
Or the ComonServiceImpl.java
#Transactional
public class CommonServiceImpl implements CommonService{
private EntityManager em;
#PersistenceContext(unitName="pu1")
public void setEntityManager(EntityManager em) {
this.em = em;
}
// MTD added for explicit order by
#SuppressWarnings("unchecked")
public List<Object> findAll(String name) {
getEntityManager().clear();
String sql = "select a FROM " + name + " a";
Query query = getEntityManager().createQuery(sql);
return query.getResultList();
}
//...(other sql selects, updates, inserts)
}
LoginAction.java
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private CommonService service;
private String username;
private String password;
private String environment;
public LoginAction(CommonService service) {
this.service = service;
}
public String execute() throws Exception {
return Action.SUCCESS;
}
#SuppressWarnings({ "unchecked", "static-access" })
public String login() throws Exception {
//Encrypt input password
CEncrypt cEncrypt = new CEncrypt();
String encryptedPwd = cEncrypt.encryptString(password);
//Get user by Username
User user = (User) service.findUser(username, User.class.getName());
//Check if input password is the same as the password in the database & login
if (user!=null && user.getPassword().equals(encryptedPwd)) {
#SuppressWarnings("rawtypes")
Map session = ActionContext.getContext().getSession();
session.put("logged-in","true");
session.put("loggedIn", "true");
session.put("WebAdminUserID", user.getUsername());
session.put("WebAdminUsername", user.getName());
session.put("WebAdminID", user.getRole_id());
return Action.SUCCESS;
} else {
return Action.ERROR;
}
}
//...
}
UPDATE
I was able to test my connection to the datasource by manually calling the lookup. But since my website is built on the persistence unit I would like to fix that error instead of re-writing the project to call the connection directly like this:
public String getEnvironment() {
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource test = (DataSource)envCtx.lookup("jdbc/test");
Connection con = test.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from WEB_PAGE_USERS where username = 'user'");
while(rs.next()){
System.out.println("username="+rs.getString("username")+", password="+rs.getString("password")+", role id="+rs.getString("role_id"));
}
// environment = "[" + (String)envCtx.lookup("Environment") + "]";
} catch (Exception e)
{
System.out.println("Environment Exception: " + e.getMessage());
}
return environment;
}
Which does return the correct data username=user, password=password, role id=1
To fix my answer I had to add every model class I had with the #Entity annotation to my persistence.xml file. It seems that even though I am using an entityManager I still needed to specify all of the #Entity classes (normally in Tomcat the entityManager would automatically find all of the classes).
Also I was getting that [WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null. warning which was causing my session to be cleared each time a page loaded (makes it hard to stay logged in). So I increased the length to 28 in the server.xml on WebSphere.
server.xml
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>jsp-2.2</feature>
<feature>jndi-1.0</feature>
<feature>jdbc-4.0</feature>
<feature>localConnector-1.0</feature>
<feature>servlet-3.0</feature>
<feature>jaxrs-1.1</feature>
</featureManager>
<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint host="localhost" httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint"/>
<dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
<jdbcDriver id="oracle-driver" libraryRef="oracle-lib"/>
<connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
<properties.oracle URL="jdbc:oracle:thin:#crappie.local:1521:STILOG" password="password" user="user"/>
</dataSource>
<library id="oracle-lib">
<fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
</library>
<applicationMonitor updateTrigger="mbean"/>
<webApplication id="WebAdmin" location="WebAdmin.war" name="WebAdmin"/>
<httpSession idLength="28"></httpSession>
</server>
persistence.xml
<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_1_0.xsd"
version="1.0">
<persistence-unit name="pu1">
<class>com.model.App</class>
<class>com.model.AudioType</class>
<class>com.model.AuditRevisionEntity</class>
<class>com.model.ClosedGroup</class>
<class>com.model.ClosedSchedule</class>
<class>com.model.ClosedScheduleGroup</class>
<class>com.model.Department</class>
<class>com.model.Dnis</class>
<class>com.model.DnisVoiceTalent</class>
<class>com.model.GlobalXferGroupTemplate</class>
<class>com.model.Language</class>
<class>com.model.Location</class>
<class>com.model.MainMenu</class>
<class>com.model.NameValue</class>
<class>com.model.NameValueFunction</class>
<class>com.model.NameValueType</class>
<class>com.model.Peg</class>
<class>com.model.PegType</class>
<class>com.model.PharmacyConfig</class>
<class>com.model.Promo</class>
<class>com.model.PromoMessage</class>
<class>com.model.PromoSchedule</class>
<class>com.model.PromoType</class>
<class>com.model.Role</class>
<class>com.model.Schedule</class>
<class>com.model.ScheduleHours</class>
<class>com.model.ScheduleRecording</class>
<class>com.model.ScheduleType</class>
<class>com.model.Server</class>
<class>com.model.SpecialSchedule</class>
<class>com.model.SpecialScheduleRecording</class>
<class>com.model.Store</class>
<class>com.model.StoreAudio</class>
<class>com.model.StoreClosedGroup</class>
<class>com.model.StoreDepartment</class>
<class>com.model.StorePromo</class>
<class>com.model.StoreSchedule</class>
<class>com.model.StoreSpcSchedule</class>
<class>com.model.StoreType</class>
<class>com.model.StoreXferGroup</class>
<class>com.model.SystemMaintenance</class>
<class>com.model.TargetSystem</class>
<class>com.model.Timezone</class>
<class>com.model.Title</class>
<class>com.model.User</class>
<class>com.model.UserWebPage</class>
<class>com.model.UserWebPageAccess</class>
<class>com.model.UserWebPageClassType</class>
<class>com.model.VoiceTalent</class>
</persistence-unit>
</persistence>

Angularjs $http.post data not binding with backend pojo

I have searched the net and found few solution,but still i am facing the same problem.
I am trying to create a web application with Angularjs as frontend end spring rest as back end.
I am able to access the url resource through $http.post methos, but while the binding of data to pojo doesnt happen. The values are always null.
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>login</display-name>
<servlet>
<servlet-name>springws</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springws</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
My dispatcher servlet configuration
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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:component-scan base-package="com.junaid.spring.webservice" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<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>
<!-- Drop and re-create the database schema on startup -->
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
</beans>
Angualrjs controller file
login.controller('RegisterController',['$scope','userFactory', function($scope, userFactory) {
$scope.user;
$scope.saveUser = function(){
userFactory.saveUser($scope.user);
};
}]);
Angularjs factory js file
angular.module('login')
.factory('userFactory' , ['$http', function($http){
var userFactory= {};
userFactory.authenticate = function(user){
console.log(user.name);
console.log(user.password);
};
userFactory.saveUser = function(user){
console.log(user.name);
console.log(user.password);
console.log(user.phone);
console.log(user.email);
$http.post('rest/register', user).success(console.log("registered"));
};
userFactory.forgotPassword = function(user){
console.log(user.name);
};
return userFactory;
}]);
Jsp page invokes userFactory.saveUser() function which in turns call my rest service,
my controller class
#Controller
public class UserController {
#RequestMapping(value = "/authenticate", method = RequestMethod.GET)
public #ResponseBody String getState(UserData ud) {
System.out.println(ud.getPassword());
return "true";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public #ResponseBody String registerUser(Users ud) {
System.out.println(ud.getPassword());
return "true";
}
}
The println statements always prints null.
Can anyone tell me where i am going wrong.
You need the #RequestBody in your getState and registerUser methods before the Argument. Furthermore getState must be a POST Method.
#Controller
public class UserController {
#RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public #ResponseBody String getState(#RequestBody UserData ud) {
System.out.println(ud.getPassword());
return "true";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public #ResponseBody String registerUser(#RequestBody Users ud) {
System.out.println(ud.getPassword());
return "true";
}
}

Problems with Autowired and Spring Injection [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 8 years ago.
SOLVED
Lately I've been having problems with an Spring MVC application which I'm trying to develop.
The main problem is that I don't know exactly why the #Autowired annotation is not working properly and that's probably because I have something wrong. I'm going to post here my code so you can help me with my issue! Thanks a lot guys:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>HelloWorld Application</display-name>
<description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
</description>
<servlet>
<servlet-name>webDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webDispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.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-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<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.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="securityDao"
class="com.agrichem.server.model.repositories.impl.SecurityDaoImpl">
</bean>
</beans>
webDispatcher-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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.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-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- <import resource="spring-security-web.xml"/> -->
</beans>
SecurityDao.java
public interface SecurityDao {
public boolean validateUser(User user);
public User authenticateUser(User user);
public User getUser (User user);
}
SecurityDaoImpl.java
#Repository("securityDao")
public class SecurityDaoImpl extends HibernateDao implements SecurityDao {
public SecurityDaoImpl() {
super();
}
#Override
public boolean validateUser(User user) {
Query query = openSession()
.createQuery(
"from User u where u.login = :login and u.password = :password");
query.setParameter("login", user.getLogin());
query.setParameter("password", user.getPassword());
return (query.list().size() > 0) ? true : false;
}
#Override
public User authenticateUser(User user) {
Query query = openSession()
.createQuery(
"from User u where u.login = :login and u.password = :password");
query.setParameter("login", user.getLogin());
query.setParameter("password", user.getPassword());
return (User) query.uniqueResult();
}
#Override
public User getUser(User user) {
Query query = openSession().createQuery(
"from User u where u.login = :login");
query.setParameter("login", user.getLogin());
return (User) query.uniqueResult();
}
}
WebSecurityConfig.java
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(new CustomUserDetailsService());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/home/logout.do").permitAll()
.anyRequest().authenticated().and().formLogin()
.loginPage("/home/login.do").permitAll()
.failureUrl("/home/accessdenied.do").permitAll();
}
}
CustomUserDetailsService.java
#Configurable
#Transactional
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
#Qualifier("securityDao")
private SecurityDao securityDAO;
#Override
public UserDetails loadUserByUsername(String arg0)
throws UsernameNotFoundException {
com.agrichem.server.model.security.User user = securityDAO
.getUser(new com.agrichem.server.model.security.User(arg0, ""));
User userDetails = new User(user.getLogin(), user.getPassword(),
getGrantedAuthorities(user.getRoles()));
return userDetails;
}
public static List<GrantedAuthority> getGrantedAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
public SecurityDao getSecurityDAO() {
return securityDAO;
}
public void setSecurityDAO(SecurityDao securityDAO) {
this.securityDAO = securityDAO;
}
}
In this point when I try to login to the application and I'm gonna check the Dao to access to the database I'm getting the 'securityDao' property null. Exactly in CustomUserDetailsService in the following line : com.agrichem.server.model.security.User user = securityDAO.getUser(new com.agrichem.server.model.security.User(arg0, "")); and obvisously I'm getting a NullPointerException.
org.springframework.security.authentication.InternalAuthenticationServiceException
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.agrichem.server.services.security.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:35)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
... 36 more
Solution:
Found it! The problem was that in WebSecurityConfig I was doing the following:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(**new CustomUserDetailsService()**);
}
and then the new instance of CustemUserDetailsService was out of the Spring Control.
To solve it I added in CustomUserDetailsService a constructor:
private SecurityDao securityDAO;
public CustomUserDetailsService(SecurityDao securityDAO) {
super();
this.securityDAO = securityDAO;
}
and I modified WebSecurityConfig in this way:
#Autowired
private SecurityDao securityDao;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(new CustomUserDetailsService(securityDao));
}
Thanks anyway for your help!
Eventhough you have solved this issue, the solution is ugly in terms of Spring Dependency Injection and Inversion of Control theories.
Basically you should never use the new keyword to instantiate objects if you are using Spring. Because all objects must be instantiated and injected only by the Spring Container.
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.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-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<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.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="securityDao"
class="com.agrichem.server.model.repositories.impl.SecurityDaoImpl">
</bean>
<bean id="customerService"
class="com.agrichem.server.path.to.service.CustomUserDetailsService">
</bean>
</beans>
WebSecurityConfig.java
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService customUserDetailsService
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(customUserDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/home/logout.do").permitAll()
.anyRequest().authenticated().and().formLogin()
.loginPage("/home/login.do").permitAll()
.failureUrl("/home/accessdenied.do").permitAll();
}
}
And you should have a Default Constructor for CustomUserDetailsService which doesn't take in any arguments. All your #Autowired properties should be inject by the spring container.
Furthermore you are intermixing Spring Java Configuration and Spring XML Configuration which is fine, but it is better if you decide on one particular method to define your beans.

Spring + Hibernate console application

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

Categories

Resources