Getting Error in Spring Mvc - java

I am getting following error....
java.lang.IllegalStateException: **Neither BindingResult nor plain target object for bean name 'course' available as request attribute**
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
at
Model Class:
#Entity
#Table(name="course" ,schema = "practise5")
public class Course implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#GeneratedValue(strategy=GenerationType.AUTO)
#Id
private int id;
#Column(name="Name")
private String Name;
#ManyToMany(mappedBy="courseSet")
private Set<Person> personSet;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public Set<Person> getPersonSet() {
return personSet;
}
public void setPersonSet(Set<Person> personSet) {
this.personSet = personSet;
}
}
Controller:
#RequestMapping(value="/addCourse",method= RequestMethod.POST)
public #ResponseBody String addCourse(#ModelAttribute("course") Course course, Model model)
{
courseServise.addcourse(course);
return "redirect:addEmployee";
}
Jsp:
<form:form commandName="course" action="addCourse" method="POST">
<form:input path="CourseName" id="course" required="required"/>
<input type="submit" value="Submit">
</form:form>
............................................................................................................................................................
<context:annotation-config />
<context:component-scan base-package="com.spring" />
<mvc:annotation-driven />
<mvc:resources location="/WEB-INF/" mapping="/**" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="resources/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}" />
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.spring.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop> -->
</props>
</property>
</bean>

I just add the following code in my controller...
Second thing is that you have to first redirect your index.jsp file to some other file...
#RequestMapping(method = RequestMethod.GET)
public String addEmployee(#ModelAttribute("a") A a, Model model,HttpServletRequest request)
{
return "addEmployee";
}

You don't match the correct URL in your JSP file.
Change this line on your JSP file :
<form:form commandName="course" action="addCourse" method="POST">
For:
<form:form commandName="course" action="/addCourse" method="POST">
Else, you can change your mapping on your controller:
#RequestMapping(value="/addCourse",method= RequestMethod.POST)
For:
#RequestMapping(value="addCourse",method= RequestMethod.POST)

as said in this post, error might occur while loading the jsp itself, and
more over binding might fail for below reasons
The binding results can be examined via the BindingResult interface,
extending the Errors interface: see the getBindingResult() method.
Missing fields and property access exceptions will be converted to
FieldErrors, collected in the Errors instance, using the following
error codes:
> Missing field error: "required"
> Type mismatch error: "typeMismatch"
> Method invocation error: "methodInvocation"
so check any type mismatches or field you might have missed, as i had faced this issue personally

Related

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion

I'm newer in java development. I want to add validators to our project. But I had a problem. Please help me!
I add
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
in my pom.xml .My project is a Maven Modules Project.
My MVC Config:
<bean
id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property
name="providerClass"
value="org.hibernate.validator.HibernateValidator" />
<property
name="validationMessageSource"
ref="messageSource" />
</bean>
<bean
id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:development/messages</value>
</list>
</property>
<property
name="useCodeAsDefaultMessage"
value="false" />
<property
name="defaultEncoding"
value="UTF-8" />
<property
name="cacheSeconds"
value="60" />
</bean>
And my DTO:
public class User4BlackListRequest implements Serializable {
private static final long serialVersionUID = -4886429042153823406L;
#Size(max=4,min=2,message="realName's length must be 2 ~ 4")
private String realName;
private Integer isDelete;
private UserTypeEnum userType;
public User4BlackListRequest(){}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public void setUserType(UserTypeEnum userType) {
this.userType = userType;
}
public UserTypeEnum getUserType() {
return userType;
}
}
User4BlackListResponse
public class User4BlackListResponse implements Serializable {
private static final long serialVersionUID = -4175005832458864444L;
private String userId;
private String realName;
private UserTypeEnum userType;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public UserTypeEnum getUserType() {
return userType;
}
public void setUserType(UserTypeEnum userType) {
this.userType = userType;
}
}
controller
#RequestMapping(value="/getList4BlackList",method=RequestMethod.GET)
#ResponseBody
public DataResult<PageInfo<User4BlackListResponse>> getList4BlackList (#Valid User4BlackListRequest request,Errors result, PageParam pageParam,SortParam sortParam){
if(result.hasErrors()){
String msg = result.getAllErrors().get(0).getDefaultMessage();
logger.info(msg);
}
return DataResult.SuccessData(userService.getList4BlackList(request, pageParam, sortParam));
}
then I test, but log show:
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]->org.springframework.validation.BeanPropertyBindingResult["model"]->java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]->org.springframework.validation.BeanPropertyBindingResult["model"]->java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]->org.springframework.validation.BeanPropertyBindingResult["model"]->java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]-....at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:706) at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:633)
at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:536)
at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:30)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690)
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"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
<mvc:annotation-driven validator="validator" />
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="userScheduledManager" method="editActive" cron="0 0/15 * * * *"/>
<task:scheduled ref="invitScheduledManager" method="expireInvite" cron="0 0/60 * * * *"/>
</task:scheduled-tasks>
<task:scheduler id="myScheduler" pool-size="10"/>
<bean id="apiObjectMapper"
class="com.xxxxx.zpxt.common.convert.ApiObjectMapper">
<constructor-arg name="jsonDefaultValue" value="true"></constructor-arg>
<property name="timeZone">
<bean class="java.util.TimeZone" factory-method="getTimeZone">
<constructor-arg value="GMT+08" />
</bean>
</property>
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
<context:component-scan base-package="com.xxxxx.zpxt">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"
scope="singleton" lazy-init="true">
<property name="corePoolSize" value="4" />
<property name="maxPoolSize" value="80" />
<property name="queueCapacity" value="500" />
</bean>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean
class="com.xxxxx.zpxt.common.convert.ValueToEnumConverterFactory" />
<bean
class="com.xxxxx.zpxt.common.convert.StringToDateConverter"></bean>
</list>
</property>
</bean>
<bean id="loggerMethodInterceptor" class="com.xxxxx.zpxt.common.interceptor.LoggerMethodInterceptor"/>
<bean id="repeatSubmitMethodInterceptor" class="com.xxxxx.zpxt.common.interceptor.RepeatSubmitMethodInterceptor"/>
<bean id="kickoutMethodInterceptor" class="com.xxxxx.zpxt.common.interceptor.KickoutMethodInterceptor"/>
<bean id="cacheServiceInterceptor" class="com.xxxxx.zpxt.common.interceptor.CacheServiceInterceptor"/>
<bean
id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property
name="providerClass"
value="org.hibernate.validator.HibernateValidator" />
<property
name="validationMessageSource"
ref="messageSource" />
</bean>
<bean
id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
</list>
</property>
<property
name="useCodeAsDefaultMessage"
value="false" />
<property
name="defaultEncoding"
value="UTF-8" />
<property
name="cacheSeconds"
value="60" />
</bean>
</beans>
servlet-context.xml
<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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<context:component-scan base-package="com.xxxxx.zpxt.controller"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:component-scan
base-package="com.xxxxx.zpxt.shiro.web.controller"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven conversion-service="conversionService">
<mvc:argument-resolvers>
<bean
class="com.xxxxx.zpxt.controller.util.CurrentUserMethodArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
<aop:config>
<aop:pointcut id="webMethodPointcut"
expression="execution(* com.xxxxx.zpxt.controller.*.*.*(..)) and
#annotation(org.springframework.web.bind.annotation.RequestMapping)" />
<aop:advisor advice-ref="loggerMethodInterceptor" pointcut-ref="webMethodPointcut" order="1"/>
<aop:advisor advice-ref="kickoutMethodInterceptor" pointcut-ref="webMethodPointcut" order="2"/>
<aop:advisor advice-ref="repeatSubmitMethodInterceptor" pointcut-ref="webMethodPointcut" order="3"/>
</aop:config>
<mvc:default-servlet-handler />
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<bean id="defaultViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="1">
<property name="contentType" value="text/html" />
<property name="prefix" value="/" />
<property name="suffix" value="" />
</bean>
<bean id="handlerExceptionResolver"
class="com.xxxxx.zpxt.common.exception.BusinessHandlerExceptionResolver">
<constructor-arg name="objectMapper" ref="apiObjectMapper"></constructor-arg>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="20971520" />
<property name="maxInMemorySize" value="4096" />
</bean>
<import resource="classpath*:/mvc-module/*-module.xml" />
</beans>
I have no idea what's wrong. I google,but I can't find something else like this, pls help me. thank you!
According to m4gic's suggestion.I try code a demo:
controller
#RequestMapping(value="/index")
#ResponseBody
public DataResult<User> index(#Valid User request,Errors errors){
User user = new User();
DataResult<User> result = new DataResult<>();
if(errors.hasErrors()){
result.setMsg(errors.getAllErrors().get(0).getDefaultMessage());
}
result.setData(user);
return result;
}
User.java
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#NotBlank(message = "name is null!")
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DataResult.java
public class DataResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
private int code;
private String msg;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
But It works well.NO error;Result:
{
"code": 0,
"msg": "name is null!",
"data": {
"name": null,
"age": 0
}
}
I think what you definitely can do is to try to handle validation errors in different way.
Maybe the problem is that you are trying to handle errors in a controller function having #ResponseBody that would mean that the error should be given back as json. If you would use controlleradvice or custom exception handler, that may help you out.
The other thing you can do is to create a proper spring boot project (after figuring out that using boot 1.4.0.RELEASE will create a project that will contain spring 4.3.2.RELEASE and everything else that is compatible). Then try to reproduce your error in this project (with boot-controlled compatible dependency-set). If there is no error, then you have to compare the two projects dependency tree, because very probably you are using some incompatible jars.
Since you are using Hibernate, check if you have bidirectional mapping. Those can cause infinite recursion. For example if you have parent class A and child class B, and A has list of B`s but B also have reference to its parent A. This will be major problem for serialization. Solution is to either break bidirectional mapping or implement some kind of guard to not populate field of type A in class B.

HibernateException: saveOrUpdate is not valid without active transaction

Perhaps this question has been asked severally but am not able to find a solution to this. I am new to Spring and trying to working on a simple project to integrate Spring with Hibernate 4 using annotations. Whenever i click the user form to save to DB it throws this exception:
HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: saveOrUpdate is not valid without active transaction
What am I doing wrong? My code is below:
User.java
#Entity
#Table(name="SpringUsers")
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "userId")
private int id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UsDAOImpl.java
#Repository
public class UserDAOImpl implements UserDAO{
#Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(){}
public UserDAOImpl( SessionFactory sessionFactory){
this.sessionFactory= sessionFactory;
}
#Override
#Transactional
public List<User> list() {
List<User> listUser = sessionFactory.getCurrentSession()
.createCriteria(User.class).list();
return listUser;
}
#Override
#Transactional
public void saveOrUpdate(User user) {
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
#Override
#Transactional
public void delete(int id) {
User userToDelete = new User();
userToDelete.setId(id);
sessionFactory.getCurrentSession().delete(userToDelete);
}
#Override
#Transactional
public User get(int i) {
String hql = "from User where id=" + i;
Query query = sessionFactory.getCurrentSession().createQuery(hql);
List<User> listUser = (List<User>) query.list();
if (listUser != null && !listUser.isEmpty()) {
return listUser.get(0);
}
return null;
}
}
user-servlet.xml
<context:component-scan base-package="com.myspringapp.controller"/>
<mvc:annotation-driven/>
<context:annotation-config />
<!-- <tx:annotation-driven />-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE"/>
<property name="username" value="system"/>
<property name="password" value="henry"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.myspringapp.model.User</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<constructor-arg ref="sessionFactory"/>
</bean>
<bean id="userDao" class="com.myspringapp.dao.UserDAOImpl">
<constructor-arg ref="sessionFactory"/>
</bean>
<!-- <tx:annotation-driven transaction-manager="transactionManager"/>-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
Uncomment this line and it should work:
<tx:annotation-driven />

Spring/Hibernate Write operations are not allowed in read-only mode

I've read some of other questions on the same topic, but in my case I'm not actually specifying anything. What makes me really confused is I have another call that works. I don't specify any transactions so I'm not sure why this is becoming a problem.
This is what happens when I try to use xssSave() (in the service class at the bottom), but sqlInject (also in the same class) works fine. As far as I can tell these operate identically except that one works and one doesn't.
If you want to view the full code and/or check it out yourself, it's available on GitHub (https://github.com/tenmilez/WebBilly).
Spring configuration (split into 3 files):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
<import resource="recipeasy-aspects.xml" />
-->
<import resource="webbilly-data.xml"/>
<import resource="webbilly-spring.xml"/>
<import resource="webbilly-service.xml"/>
<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/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order">
<value>0</value>
</property>
<property name="mappings">
<props>
<prop key="welcome.htm">welcomeController</prop>
<prop key="sqli.htm">SQLiController</prop>
<prop key="xss.htm">XssController</prop>
</props>
</property>
</bean>
<bean id="paramResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="method"/>
<property name="defaultMethodName" value="onInitPage"/>
</bean>
<bean id="welcomeController" class="com.webbilly.web.WelcomeController"/>
<bean id="SQLiController" class="com.webbilly.web.SQLiController">
<property name="methodNameResolver" ref="paramResolver"/>
<property name="sqliServices" ref="sqliServices"/>
</bean>
<bean id="XssController" class="com.webbilly.web.XssController">
<property name="methodNameResolver" ref="paramResolver"/>
<property name="sqliServices" ref="sqliServices"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="sqliServices" class="com.webbilly.service.SQLiServices">
<property name="sqliDataDAO" ref="sqliDataDAOhibernate"/>
<!--
<property name="sqliDataDAO" ref="sqliDataDAOjdbc" />
<property name="sqliDataDAO" ref="sqliDataDAOhibernate" />
-->
<property name="xssDataDAO" ref="xssDataDAO"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="jdbcDataSource"/>
<property name="mappingDirectoryLocations">
<value>classpath:/com/webbilly/dao/hibernate/hbm</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.dialect">${database.dialect}</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="genericDAO" class="com.webbilly.dao.hibernate.GenericDAO"
abstract="true">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="sqliDataDAOhibernate" parent="genericDAO">
<constructor-arg>
<value>com.webbilly.domain.SQLiData</value>
</constructor-arg>
</bean>
<bean id="xssDataDAO" parent="genericDAO">
<constructor-arg>
<value>com.webbilly.domain.XssData</value>
</constructor-arg>
</bean>
<bean id="sqliDataDAOjdbc" class="com.webbilly.dao.jdbc.SQLiDAO">
<property name="dataSource" ref="jdbcDataSource"/>
</bean>
<bean id="jdbcDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="connectionProperties">
<props>
<prop key="allowMultiQueries">true</prop>
</props>
</property>
</bean>
</beans>
My data objects (is there a name for these? Always referred to them as domain objects, but I'm not sure if that's widely accepted terminology).
package com.webbilly.domain;
/**
* Created by christopher on 12/12/14.
*/
public class XssData {
private int id;
private String userName;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.webbilly.domain;
/**
* Created by christopher on 12/3/14.
*/
public class SQLiData {
private String id;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
The persistence layer
package com.webbilly.dao;
import java.util.Collection;
public interface IGenericDAO<T> {
void save(T t);
Collection<T> getAll();
T getById(int id);
void delete(int id);
}
package com.webbilly.dao.hibernate;
import com.webbilly.dao.IGenericDAO;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import java.util.Collection;
public class GenericDAO<T> extends HibernateDaoSupport implements IGenericDAO<T> {
/**
* ******************************************************
* ********* Accessors and private members ****************
* *******************************************************
*/
private Class<T> type;
public GenericDAO(Class<T> type) {
this.type = type;
}
public T getById(int id) {
return (T) getHibernateTemplate().get(type, id);
}
public Collection<T> getAll() {
return getHibernateTemplate().loadAll(type);
}
public void save(T t) {
getHibernateTemplate().saveOrUpdate(t);
}
public void delete(int id) {
getHibernateTemplate().delete(getById(id));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.webbilly.domain">
<class name="SQLiData" table="sqli">
<id column="id" name="id" type="int">
<generator class="increment"/>
</id>
<property name="value" type="string">
<column name="value"/>
</property>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.webbilly.domain">
<class name="XssData" table="xss">
<id column="id" name="id" type="int">
<generator class="increment"/>
</id>
<property name="userName" type="string">
<column name="user_name"/>
</property>
<property name="message" type="string">
<column name="message"/>
</property>
</class>
</hibernate-mapping>
The service layer (it really is just one class; my application is not that big yet).
package com.webbilly.service;
import com.webbilly.dao.IGenericDAO;
import com.webbilly.domain.SQLiData;
import com.webbilly.domain.XssData;
import java.util.Collection;
/**
* Created by christopher on 12/3/14.
*/
public class SQLiServices {
private IGenericDAO<SQLiData> sqliDataDAO;
private IGenericDAO<XssData> xssDataDAO;
public void sqlInject(String str) {
SQLiData sqliData = new SQLiData();
sqliData.setValue(str);
getSqliDataDAO().save(sqliData);
}
public void xssSave(XssData data) {
xssDataDAO.save(data);
}
public Collection<XssData> getAllPosts() {
return xssDataDAO.getAll();
}
public IGenericDAO<SQLiData> getSqliDataDAO() {
return sqliDataDAO;
}
public void setSqliDataDAO(IGenericDAO<SQLiData> sqliDataDAO) {
this.sqliDataDAO = sqliDataDAO;
}
public IGenericDAO<XssData> getXssDataDAO() {
return xssDataDAO;
}
public void setXssDataDAO(IGenericDAO<XssData> xssDataDAO) {
this.xssDataDAO = xssDataDAO;
}
}
HibernateTemplate doesn't manage transactions, you need a HibernateTransactionManager instead.
The write operations need to execute within the context of a transaction, so you need to also annotate you DAO or your services with #Transactional.

Spring JpaTransactionManager with Nested transactions

I have following spring configuration.
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="nestedTransactionAllowed" value="true" />
</bean>
<bean id='entityManagerFactory'
class='org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean'>
<property name="persistenceUnitName" value="test" />
<property name='dataSource' ref='dataSource' />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
</property>
</bean>
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<property name="username" value="test" />
<property name="password" value="test" />
</bean>
And i have created following entity.
#Entity(name="testtable")
public class Testtable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private int testid;
#Column(length=10)
private String description;
public Testtable() {
}
public int getTestid() {
return this.testid;
}
public void setTestid(int testid) {
this.testid = testid;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
Now I want to test the nested transaction behavior with this setup. So I have created following test class.
#TransactionConfiguration(defaultRollback=false)
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:context-test.xml")
public class TableTest {
#Autowired
private TesttableRepository testtableRepository;
#Test
#Transactional
public void testMethod()
{
Testtable entry = new Testtable();
entry.setDescription("ABC");
entry = testtableRepository.save(entry);
TestObj t = new TestObj(testtableRepository);
t.testNestedTransactional();
entry.setDescription("ABCEE");
testtableRepository.save(entry);
assertNotNull(entry.getTestid());
}
}
public class TestObj {
public TestObj(TesttableRepository testtableRepository){
this.testtableRepository = testtableRepository;
}
private TesttableRepository testtableRepository;
#Transactional(propagation=Propagation.NESTED )
public void testNestedTransactional(){
Testtable entry1 = new Testtable();
entry1.setDescription("RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR");
testtableRepository.save(entry1);
}
}
The testNestedTransactional() method in TestObj.java should fail because of database constraint violation (Max length for field description is 10). Even though this method fail I expect "ABCEE" value to be saved in database. Is this correct with nested transaction behavior? How can I achieve this goal?
The problem is that you create TestObj manually. You should do it using Spring context (declare it in context as a bean and autowire in the test).
Spring will wrap this bean in a proxy to make it transactional. In your case it is a plain old Java object without transactional behavior.

How to use HibernateTemplate directly in my testing code

I'm trying to make a quick small test on HibernateTemplate. But I always get exception: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here.
How can I make the code work? Here're the codes:
The SpringDao.java:
package com.question;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import com.lavin.test.app.dao.hibernate.a.PersonC;
import com.lavin.test.app.dao.hibernate.a.PersonCId;
import com.lavin.test.app.net.ISimpleServerRunner;
public class SpringDao {
private HibernateTemplate hibernateTemplate = null;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory, false);
}
public static ApplicationContext ctx = new ClassPathXmlApplicationContext("dao.xml");
private static SpringDao springRunner = (SpringDao) ctx.getBean("springDao");
public static SpringDao getInstance() {
return springRunner;
}
PersonC newPC(String str) {
PersonC p0 = new PersonC();
PersonCId i0 = new PersonCId();
i0.setFirstname(str);
i0.setLastname(str);
p0.setId(i0);
return p0;
}
void test1() {
PersonC p = new PersonC();
PersonCId id = new PersonCId();
id.setFirstname("b");
id.setLastname("b");
p.setId(id);
springRunner.getHibernateTemplate().save(p);
}
public static void main(String[] s) throws Exception {
new SpringDao().test1();
}
/**
* #return Returns the hibernateTemplate.
*/
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
}
dao.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/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:annotation-config />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
lazy-init="true">
<property name="driverClass">
<value>${jdbc.driverClassName}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="initialPoolSize">
<value>5</value>
</property>
<property name="minPoolSize">
<value>5</value>
</property>
<property name="maxPoolSize">
<value>30</value>
</property>
<property name="idleConnectionTestPeriod">
<value>10</value>
</property>
<property name="testConnectionOnCheckin">
<value>true</value>
</property>
<property name="maxIdleTime">
<value>1800</value>
</property>
<property name="properties">
<props>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
</props>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingLocations">
<value>classpath:com/question/*.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect}
</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.use_second_level_cache">
true
</prop>
<prop key="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">
ehcache-hibernate.xml
</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="txProxyTemplate" lazy-init="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref local="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="test*">PROPAGATION_REQUIRED</prop>
<prop key="oper*">PROPAGATION_MANDATORY</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
<prop key="nTest*">PROPAGATION_REQUIRES_NEW</prop>
</props>
</property>
</bean>
<bean id="springDaoTarget" parent="txProxyTemplate">
<property name="target">
<ref local="springDao" />
</property>
</bean>
<bean id="springDao" class="com.question.SpringDao">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
and Hibernate mapping files:
package com.question;
import java.io.Serializable;
public class PersonCId implements Serializable {
private String firstname;
private String lastname;
public PersonCId() {
}
public PersonCId(String firstName, String lastName) {
this.firstname = firstName;
this.lastname = lastName;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
package com.question;
import java.util.HashSet;
import java.util.Set;
public class PersonC {
private int age;
private PersonCId id;
private Set addresses;
public PersonC() {
}
private Set emailAddresses = new HashSet();
public Set getEmailAddresses() {
return emailAddresses;
}
public void setEmailAddresses(Set emailAddresses) {
this.emailAddresses = emailAddresses;
}
private Set events = new HashSet();
// Defensive, convenience methods
protected Set getEvents() {
return events;
}
protected void setEvents(Set events) {
this.events = events;
}
/**
* #return Returns the addresses.
*/
public Set getAddresses() {
return addresses;
}
/**
* #param p_addresses
* The addresses to set.
*/
public void setAddresses(Set p_addresses) {
addresses = p_addresses;
}
/**
* #return Returns the age.
*/
public int getAge() {
return age;
}
/**
* #param p_age
* The age to set.
*/
public void setAge(int p_age) {
age = p_age;
}
/**
* #return Returns the id.
*/
public PersonCId getId() {
return id;
}
/**
* #param p_id
* The id to set.
*/
public void setId(PersonCId p_id) {
id = p_id;
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.question.PersonC" table="PERSONC">
<composite-id name="id" class="com.question.PersonCId">
<key-property name="firstname" type="string">
<column name="firstname" length="50"/>
</key-property>
<key-property name="lastname" type="string">
<column name="lastname" length="50"/>
</key-property>
</composite-id>
<property name="age"/>
</class>
</hibernate-mapping>
I think you are trying to use unwrapped object instead of proxy enriched with transactional behavior. Your initialization should be:
private static SpringDao springRunner = (SpringDao) ctx.getBean("springDaoTarget");
Alter your names accordingly too. By the way TransactionProxyFactoryBean is considered "old style" nowadays. You may consider using #Transactional instead.

Categories

Resources