I have a project in Spring, where I have 2 connections to the database. Two because one is for read-only connections and the other is for read-write connections.
My problem is, when I try to invoke method to read only, I get:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
Now I don't know, how to exactly configure my connections.
Below I've inserted my SERVICE CLASS file. The problem is when I'm trying to invoke method with sessionFactoryr , when I'm using sessionFactory - everything is OK.
My configuration is:
hibernate-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:p="http://www.springframework.org/schema/p"
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-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
">
<context:property-placeholder location="/WEB-INF/spring.properties" />
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven transaction-manager="transactionManagerr" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<!-- First Connection -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.esb.scs"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${app.jdbc.username}"
p:password="${app.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<!-- Second connection (read only) -->
<bean id="sessionFactoryr" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSourcer"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.esb.scs"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSourcer" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${appr.jdbc.username}"
p:password="${appr.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManagerr" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactoryr" />
</beans>
Service Class:
package com.esb.scs.service;
import static java.lang.System.out;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.esb.scs.domain.User;
import com.esb.scs.domain.UserReference;
#Service("userService")
#Transactional
public class UserService {
protected static Logger logger = Logger.getLogger("service");
// #Resource(name="sessionFactoryr")
// private SessionFactory sessionFactoryr;
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
#Resource(name="sessionFactoryr")
private SessionFactory sessionFactoryr;
public void addUser(HttpServletRequest request){
logger.info("test");
Session session = sessionFactory.getCurrentSession();
PasswordEncoder encoder = new Md5PasswordEncoder();
String hashedPassword = encoder.encodePassword(request.getParameter("password"), null);
String login = request.getParameter("login");
String password = hashedPassword;
//String role = request.getParameter("role");
String role = "normal";
String ip = request.getParameter("ip");
int active = 1;
String referenceAddress = request.getParameter("referer");
String sex = request.getParameter("sex");
int age = Integer.parseInt(request.getParameter("age"));
String country = request.getParameter("country");
String city = request.getParameter("city");
String education = request.getParameter("education");
String profession = request.getParameter("profession");
String branch = request.getParameter("branch");
Transaction transaction = session.beginTransaction();
User user = new User();
UserReference userReference = new UserReference();
Date dateCreate = new Date();
user.setEmail(login);
user.setPassword(password);
user.setRole(role);
user.setIp(ip);
user.setDateCreate(dateCreate);
user.setLastLoginDate(dateCreate);
user.setActive(active);
user.setToken("");
userReference.setReferenceAddress(referenceAddress);
userReference.setSex(sex);
userReference.setAge(age);
userReference.setCountry(country);
userReference.setCity(city);
userReference.setEducation(education);
userReference.setProfession(profession);
userReference.setBranch(branch);
userReference.setSite(referenceAddress);
userReference.setUser(user);
userReference.setUser(user);
user.getUserReferences().add(userReference);
session.save(user);
session.save(userReference);
transaction.commit();
}
public List<User> getUser(String name, String password){
Session session = sessionFactoryr.getCurrentSession();
String sqlQuery = "FROM User WHERE email='"+name+"' AND password = '" +password+ "'" ;
Query query = session.createQuery(sqlQuery).setMaxResults(1);
return query.list();
}
public void updateUUID(String uuid, String login, String password){
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "update User set token = :token where email = :login and password = :password";
Query query = session.createQuery(hql);
query.setString("token", uuid);
query.setString("login", login);
query.setString("password", password);
query.executeUpdate();
transaction.commit();
}
}
In addition, I have
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
in my web.xml.
According to your advice, if I add #Transactional("transactionManagerr") to my methods - it doesn't change anything, I still get the error.
I think you have to specify transaction manager name in #Transactional (e.g. #Transactional("transactionManagerr")) annotation. Read
Documentation and Jira
If you are using transactional annotations you do not need to manually create a transaction in your service class.
You have specifed the class is transactional this means each method will have its own transaction created by spring.
You can also specifiy transactional on each method and further specifiy read only as and when required.
If you are using two different datasources you also need to specify which transaction manager is to be used.
<bean id="transactionManagerr" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactoryr">
<qualifier value="transactionManagerr"/>
</bean>
And in yr service class you do this :
#Transactional(value = "transactionManagerr")
Also I would think about renaming everything, just appending "r" to everything is not really descriptive.
Related
I m setting up my java web application on the server but the rest controller is giving 404 error.
All is working fine on my local system.
This is my 1st project in java hibernate spring.
Below is my code:
UserLoginController.java
package org.jasyatra.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.jasyatra.model.User;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.service.UserLoginService;
import org.jasyatra.service.LoginAuthTokenService;
#RestController
public class UserLoginController {
#Autowired
UserLoginService userLoginService;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#RequestMapping(value = "/user/login", method = RequestMethod.POST, headers = "Accept=application/json")
public Map login(#RequestBody User parameters) {
List<User> loginResponse = userLoginService.login(parameters);
Map<String, String> response = new HashMap<>();
if (loginResponse.size() > 0) {
response.put("result", "true");
response.put("id", Integer.toString(loginResponse.get(0).getId()));
response.put("type", loginResponse.get(0).getType());
response.put("firstName", loginResponse.get(0).getFirstName());
response.put("lastName", loginResponse.get(0).getLastName());
response.put("permissions", loginResponse.get(0).getPermissions());
List<LoginAuthToken> responseToken = loginAuthTokenService.getLatestToken(loginResponse.get(0).getId(),loginResponse.get(0).getType());
response.put("token", responseToken.get(0).getToken());
} else {
response.put("result", "false");
response.put("message", "Invalid mobile no or password!");
}
return response;
}
}
UserLoginDAO.java
package org.jasyatra.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.jasyatra.service.HashService;
#Repository
public class UserLoginDAO {
#Autowired
private SessionFactory sessionFactory;
public List<User> login(User parameters) {
Session session = this.sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where mobileNo=:mobileNo and password=:password and status=:status");
query.setParameter("mobileNo", parameters.getMobileNo());
query.setParameter("password", HashService.getHash(parameters.getPassword(), "SHA1"));
query.setParameter("status", "active");
List<User> response = query.list();
return response;
}
}
UserLoginService.java
package org.jasyatra.service;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.jasyatra.dao.UserLoginDAO;
import org.jasyatra.dao.LoginAuthTokenDAO;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class UserLoginService {
#Autowired
UserLoginDAO userLoginDao;
#Autowired
LoginAuthTokenDAO loginAuthTokenDAO;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#Transactional
public List<User> login(User parameters) {
List<User> login = userLoginDao.login(parameters);
LoginAuthToken loginAuthToken = new LoginAuthToken();
if (login.size() > 0 && login.get(0).getId() > 0) {
try {
loginAuthToken.setLoginId(login.get(0).getId());
loginAuthToken.setLoginType(login.get(0).getType());
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
String token = HashService.getHash(generatedString, "SHA1");
loginAuthToken.setDateCreated(new Date());
loginAuthToken.setToken(token);
loginAuthTokenService.save(loginAuthToken);
} catch (Exception e) {
e.printStackTrace();
}
}
return login;
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/"/>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/jasyatra" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>org.jasyatra.model.User</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="268435456"/>
</beans:bean>
<context:component-scan base-package="org.jasyatra" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
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"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<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>
The main issue i have is, it is able to run index.jsp but not the controller. What can be the issue?
Please guide me in right direction.
Thanks
you can not open that url in browser because it is POST service, you can only open GET url in browser. you need to add a body while hitting that url to test
your service you can use postman.
no need to send "Accept" header this way, you can use however following attribute instead if you expect a json body with the post request :
#RequestMapping(value = "/user/login", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE);
if you want to get "Accept" header value of your request you can get it like :
public Map login(#RequestBody User parameters,#RequestHeader(value="Accept") String accept){
....
This is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns: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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<context:annotation-config />
<context:component-scan base-package="com" />
<context:property-placeholder location="/config.properties" />
<bean id="myDataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<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="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
And This is my Dao:
package com.dao.impl;
import com.dao.UniversityBasicInformationDao;
import com.message.Message;
import com.message.imp.UniversityMessage;
import com.model.UniversityBasicInformation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public class UniversityBasicInformationImp implements
UniversityBasicInformationDao {
#Autowired
private SessionFactory sessionFactory;
private static Logger logger;
public Message[] getAll() {
Session session = sessionFactory.getCurrentSession();
logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
List list = session.createQuery("FROM UniversityBasicInformation ").list();
session.close();
Message[] message = new Message[list.size()];
for (int i = 0; i < list.size(); i++) {
UniversityBasicInformation university = (UniversityBasicInformation) list.get(i);
UniversityMessage universityMessage = new UniversityMessage(university);
message[i] = universityMessage;
}
logger.info(message[0].getJson());
return message;
}
public Message findByName(String name) {
Session session = sessionFactory.getCurrentSession();
logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
List list = session.createQuery("FROM UniversityBasicInformation " +
"WHERE universityName = ?").setParameter(0, name).list();
session.close();
return new UniversityMessage((UniversityBasicInformation) list.get(0));
}
public Message findByID(int id) {
Session session = sessionFactory.getCurrentSession();
logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
List list = session.createQuery("FROM UniversityBasicInformation " +
"WHERE universityId = ?").setParameter(0, id).list();
session.close();
return new UniversityMessage((UniversityBasicInformation) list.get(0));
}
public void add(UniversityBasicInformation university) {
Session session = sessionFactory.getCurrentSession();
logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
Transaction tx = session.beginTransaction();
try {
session.save(university);
tx.commit();
} catch (Exception e) {
logger.error("UniversityBasicInformationDao add Exception: " + e.toString());
} finally {
session.close();
}
}
public void remove(UniversityBasicInformation university) {
Session session = sessionFactory.getCurrentSession();
logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
Transaction tx = session.beginTransaction();
try {
session.delete(university);
tx.commit();
} catch (Exception e) {
logger.error("UniversityBasicInformationDao delete Exception: " + e.toString());
} finally {
session.close();
}
}
public void update(UniversityBasicInformation university) {
Session session = sessionFactory.getCurrentSession();
logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
Transaction tx = session.beginTransaction();
try {
session.update(university);
tx.commit();
} catch (Exception e) {
logger.error("UniversityBasicInformationDao delete Exception: " + e.toString());
} finally {
session.close();
}
}
}
And this is my testDao:
package com.dao.impl;
import com.dao.UniversityBasicInformationDao;
import com.message.Message;
import org.junit.Before;
import org.junit.jupiter.api.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 javax.annotation.Resource;
import static org.junit.jupiter.api.Assertions.*;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath*:applicationContext.xml")
class UniversityBasicInformationImpTest {
#Autowired
private UniversityBasicInformationDao universityBasicInformationDao;
#Test
void getAll() {
assertFalse(universityBasicInformationDao == null);
Message[] message = universityBasicInformationDao.getAll();
assertEquals("{\"university_id\":\"1\"," +
"\"university_address_line_1\":\"1410 NE Campus Parkway \"," +
"\"university_address_line_2\":null,\"university_name\":\"University of Washington\"," +
"\"university_profile_image_id\":\"com.model.ImageObject#2802756f\"}",
message[0].getJson());
}
}
The thing is that it works well when i run tomcat server but when running the test, it throws out a NullPointerException(). I have checked many documentations online, and a lot of other questions in stackoverflow, but it just does not work for me. i was stuck here for nearly whole day, plz save me.
I have written the below code to implment the transaction management of spring using #transactional annotation. I still feel some changes are required
in my DAO layer. May I know what changes are required . Thanks in advance
#Controller
public class RestController {
#Autowired
DataServices dataServices;
#RequestMapping(value = "/v1/dist_list/{emailId}/members", method = RequestMethod.GET)
public #ResponseBody String getDistributionListMember(#PathVariable String emailId) throws Exception, SpringException {
String retStatus = null;
retStatus = dataServices.getDistributionListMember(emailId, callerId);
]
}
}
DataServices.java
package com.uniteid.services;
import com.uniteid.model.AIWSuser;
public interface DataServices {
public String getDistributionListMember(final String emailId, final String callerID) throws Exception;
}
Below is my service layer where I added the trasactional attribute
package com.uniteid.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.uniteid.dao.DataDao;
import com.uniteid.model.AIWSuser;
#Service("dataService")
public class DataServicesImpl implements DataServices {
#Autowired
DataDao dataDao;
#Transactional
public String getDistributionListMember(String emailId, String callerID)
throws Exception {
return dataDao.getDistributionListMember(emailId, callerID);
}
}
Below is my spring-config file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<context:component-scan base-package="com.uniteid.controller" />
<mvc:annotation-driven
content-negotiation-manager="contentNegociationManager" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:uniteidrest.properties" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url">
<value>${eidms.url}</value>
</property>
<property name="username">
<value>${eidms.username}</value>
</property>
<property name="password">
<value>${eidms.password}</value>
</property>
</bean>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"
/> <property name="url" value="jdbc:oracle:thin:#nyvm0467.ptc.un.org:1521:EIDMSUAT"
/> <property name="username" value="DBO_EIDMSUAT" /> <property name="password"
value="NewPassDBO_EIDMSUAT" /> </bean> -->
<bean id="contentNegociationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="ignoreAcceptHeader" value="true" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.uniteid.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.connection.pool_size">10</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="dataDao" class="com.uniteid.dao.DataDaoImpl"></bean>
<bean id="dataServices" class="com.uniteid.services.DataServicesImpl"></bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
It still feel I have not implemented the Transactional management properly in the below code. May I know what part of the code can be removed for me to implement it
package com.uniteid.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import com.uniteid.controller.RestController;
import com.uniteid.model.AIWSuser;
import com.uniteid.model.User;
public class DataDaoImpl implements DataDao
{
#Autowired
\
SessionFactory sessionFactory;
Session session = null;
Transaction tx = null;
static final Logger logger = Logger.getLogger(DataDaoImpl.class);
public String getDistributionListMember(final String emailId, final String callerID) throws Exception {
session = sessionFactory.openSession();
tx = session.beginTransaction();
final String[] returnVal2 = { "" };
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
CallableStatement stmt = null;
String returnVal = "";
stmt = connection.prepareCall("{?=call WS_Distributionlistmember(?,?)}");
stmt.registerOutParameter(1, Types.VARCHAR);
stmt.setString(2, emailId);
stmt.setString(3, callerID);
stmt.execute();
returnVal = stmt.getString(1);
logger.info("RETURN VALUE in getDistributionListMember method :::::: " + returnVal);
returnVal2[0] = returnVal;
logger.info("Return Value " + returnVal);
stmt.close();
}
});
tx.commit();
session.close();
return returnVal2[0];
}
}
Your code:
public String getDistributionListMember(final String emailId, final String callerID) throws Exception {
session = sessionFactory.openSession();//This is bad
tx = session.beginTransaction();//This is bad
tx.commit();//This is bad
session.close();//This is bad
Correct should be:
public String getDistributionListMember(final String emailId, final String callerID) throws Exception {
session = sessionFactory.getCurrentSession();//good way
It is because you told spring to autowired sessionFactory and from now on spring is managing your hibernate session not you. So getCurrentSession() is correct way.
#M. Deinum Thanks to point it out.
Remove bean declaration for bean id transactionManager and set txManager instead of transactionManager in transaction-manager value. As you are using hibernate with spring so HibernateTransactionManager should be used instead of DatabaseTransactionManager to define transaction boundary. DatabaseTransactionManager is used when you directly interact with data source without using any ORM or JPA framework.
In your service class define transaction boundary for method as below annotation
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
when i am running my spring integration junit class i am getting above exception.
here is my class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BpmControllerTest {
#Autowired
private BpmProcessorDaoImplTest bpmProcessorDao;
#Test
public void testRun() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
List<User>user=bpmProcessorDao.testRead();
Assert.assertEquals(0,user.size());
}
}
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
here is my stack trace..
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 37 more
can any body please tell me how to write this line
#ContextConfiguration(locations = "classpath:applicationContext.xml")
some places in google i found like this
#ContextConfiguration(locations = "classpath:**/applicationContext.xml")
what is the difference of these two
and when i am writing this line with stars i am getting different exception
here is my stack trace.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.tcs.test.dao.BpmProcessorDaoImplTest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 28 more
and one thing that my application is only dynamic web project no maven,no ant .
can any body please tell me how to run my test cases successfully..
here is my applicationContext.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.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/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
">
<tx:annotation-driven />
<tx:jta-transaction-manager/>
<context:component-scan base-package="com.tcs.test" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#172.19.8.159:1521/OIM.itba.gov.in" />
<property name="username" value="AppDB"></property>
<property name="password" value="AppDB"></property>
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="runScheduler" class="com.tcs.controller.BpmControllerTest" />
<task:scheduled-tasks>
<task:scheduled ref="runScheduler" method="testRun" cron="0 0/1 * * * ?" />
</task:scheduled-tasks>
</beans>
all my test java files in side test source folder.
and all the files in side the package's which prefix is com.tcs.test
here is my daoImpl class
package com.tcs.test.dao;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import com.tcs.controller.BPMConstants;
import com.tcs.controller.User;
#Repository
public class BpmProcessorDaoImplTest implements BpmProcessorDaoTest{
private static final Logger logger=Logger.getLogger(BpmProcessorDaoImplTest. class);
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
#Test
public void testWrite() {
}
#Test
public void testUpdateStatus() {
}
#Test
public List<User> testRead() {
String query=null;
List<User>users=null;
try{
// jdbcTemplate.setDataSource(dataSource);
// query=messageSource.getMessage(BPMConstants.QUERY,null,Locale.US);
query="select taskoutcome,seqNo,hash_mapdata,userid,status,taskId from com_tt_bpm_batch , "
+ "wftask where status='ACTIVE' and request_id=instanceid and state='ASSIGNED'";
logger.info("query");
jdbcTemplate.setFetchSize(20);
users=jdbcTemplate.query(query, new ResultSetExtractor<List<User>>(){
List<User> userList = new ArrayList<User>();
#SuppressWarnings("unchecked")
#Override
public List<User> extractData(ResultSet rs) throws SQLException,DataAccessException {
while(rs.next()){
logger.info("fetching records from db");
User user = new User();
user.setTaskOutcome(rs.getString(BPMConstants.TASK_OUTCOME));
user.setUserId(rs.getString(BPMConstants.USER_ID));
user.setStatus(rs.getString(BPMConstants.STATUS));
user.setTaskId(rs.getString(BPMConstants.TASK_ID));
user.setSeqNo(rs.getLong(BPMConstants.SEQ_NO));
user.setUserComment("nothing");
Blob blob=rs.getBlob(BPMConstants.HASH_MAPDATA);
try{
if(blob!=null && !blob.equals("")){
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
ByteArrayInputStream bos = new ByteArrayInputStream(blobAsBytes);
ObjectInputStream out=null;
out = new ObjectInputStream(bos);
HashMap<String, Object> map=null;
map = (HashMap<String, Object>)out.readObject();
user.setMap(map);
}
userList.add(user);
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from blob "+e.getStackTrace());
}
}
return userList;
}
});
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from db "+e.getStackTrace());
}
return users;
}
}
1)
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
The web-inf folder is not (without hacks and problems) accessabel while running the tests.
So the short and easy solution is to put that spring config files in:
(if you use maven): src\main\resources
(if you do not use maven): your java source file root folder
(if you do not use maven but eclipse): create an extra folder (for example resources), put the files in that folder, and then make this folder a eclipse source folder (right click that folder in the package explorer and then choose "Build Path" / "Use as Source Folder")
2)
your BpmProcessorDaoImplTest does not look like a valid test for me.
Either it is a Test case - then its methods have #Test annotations and the class itself have the #ContextConfiguration configuration that points to your configuration file. Or is is a Repository then it has a #Repository annotation and not #Test or #ContextConfiguration. annotations. But I never saw a class that mixed this.
So try this:
#ContextConfiguration("classpath:applicationContext.xml")
#Transactional //make your tests run in an transaction that gets rolled back after the test
public class BpmProcessorDaoImplTest {
/** Class under test */
#Autowired
private BpmProcessorDao dbmProcessorDao;
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
//just to make the example test usefull
#PersistenceContext
private EntityManager em
#Test
public void testWrite() {
DbmProcessor entity = ...;
...
this.dbmProcessorDao.save();
...
em.flush(); //make sure that every is saved before clear
em.clear(); //clear to make read(id) read the entity from the database but not from l1-cache.
int id = entity.getId();
...
DbmProcessor reloadedEntity = this.dbmProcessorDao.read(id);
//getName is just an example
assertEquals(entity.getName(), dbmProcessorDao.getName());
}
}
This will occure when applicationContext.xml cannot be found in class path
Possible solutions :
add directory containing applicationContext.xml to classpath.
give relative path of applicationContext.xml
give absolute path of applicationContext.xml
If 3rd solution worked for you would mean that applicationContext.xml was not in classpath.
I am new to spring, in my application I need to connect to Mysql, all my database's configuration are in a bean, when I try to get it,the server gives me this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
this is my servlet-context where I define my bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.metmi.mmasgis" />
<beans:bean id="dataSource" name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
autowire-candidate="true">
<beans:property name="driverClassName"
value="com.mysql.jdbc.Driver">
</beans:property>
<beans:property name="username" value="root"></beans:property>
<beans:property name="password" value="password"></beans:property>
<beans:property name="url"
value="jdbc:mysql://localhost:3306/springschema">
</beans:property>
</beans:bean>
</beans:beans>
this is my controller:
package com.metmi.mmasgis;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ContextLoader;
import com.metmi.mmasgis.dao.DbImpl;
import com.metmi.mmasgis.model.Db;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Inject
DbImpl dbs;
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
/**
* get the database list in Mysql
*/
#RequestMapping(value = "/db", method = RequestMethod.GET)
public String dbs(Locale locale, Model model) {
ApplicationContext ctx = ContextLoader
.getCurrentWebApplicationContext();
DataSource ds = (DataSource) ctx.getBean("dataSource");
dbs = new DbImpl();
dbs.setDataSource(ds);
ArrayList<Db> dbList = dbs.getDatabases();
model.addAttribute("dbList", dbList);
return "dbs";
}
/**
* Simply shows ciao.
*/
#RequestMapping(value = "/ciao", method = RequestMethod.GET)
public String ciao(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "ciao";
}
}
Move your bean declaration to your main application context, not the one where you have DispatcherServlet.