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

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.

Related

org.hibernate.MappingException: Unknown entity hibernate4 spring4

I am getting the exception
org.hibernate.MappingException: Unknown entity com.pro.entity.User
I have seen similar posts but almost all of them provides solution to change #Entity annotation to javax.persistence instead of hibernate. Which in my case wasn't useful as I am using correct annotation since the beginning. Here's the code for entity class dao and servlet context.
package com.pro.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user")
public class User {
private static final long serialVersionUID = 1L;
#Id
#Column(name="userid")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
#Column(name="password")
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Dao class code:
public User getUser(String userid)
{
Session session = this.sessionFactory.getCurrentSession();
User user = (User)session.load(User.class, userid);
return user;
}
context.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-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/orm
http://www.springframework.org/schema/orm/spring-orm-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">
<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>
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/pro?useSSL=false" />
<beans:property name="username" value="user" />
<beans:property name="password" value="password" />
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
<beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager"/><tx:annotation-driven/>
<beans:bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"></beans:bean>
<context:component-scan base-package="com.pro.controller" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans:beans>
chnage <context:component-scan base-package="com.pro.controller" />
to <context:component-scan base-package="com.pro" />
in context.xml
it should work then
Thank you guys. I got the solution.... just needed to add following in my context.xml file
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.pro.User</beans:value>
</beans:list>
</beans:property>

Getting Error in Spring Mvc

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

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.

Cannot Autowire repository service Spring JPA

I am trying to use a User repository in my code, but intellij is giving me the error.
interface is not allowed for non abstract beans
I have the following setup.
#Entity
public class User {
#Id
private long id;
private String firstName;
private String lastName;
private String profileUrl;
private String email;
private String location;
protected User(){};
public User(String first, String last, String profileUrl, String email, String location){
this.firstName = first;
this.lastName = last;
this.profileUrl = profileUrl;
this.email = email;
this.location = location;
}
public User(Person person){
this.firstName = person.getName().getGivenName();
this.lastName = person.getName().getFamilyName();
this.profileUrl = person.getImage().getUrl();
this.email = person.getEmails().get(0).getValue();
this.location = person.getCurrentLocation();
}
}
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByProfileId(long id);
}
I have tried to annotate this with #Service and #Repository but to no avail.
#Component
public class UserRepositoryImpl {
#Autowired
private UserRepository userRepository;
public void doSomething() {
List<User> byProfileId = userRepository.findByProfileId(100);
}
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:rep="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<rep:repositories base-package="com.planit.persistence.*"/>
<bean id="userRepository" class="com.planit.persistence.registration.UserRepository"/>
<!-- DB CONNECTION-->
<bean class="java.net.URI" id="dbUrl">
<constructor-arg value="#{T(com.ProjectUtils).getDBUrl()}"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url"
value="#{ 'jdbc:postgresql://' + #dbUrl.getHost() + ':' + #dbUrl.getPort() + #dbUrl.getPath() }"/>
<property name="username" value="#{ #dbUrl.getUserInfo().split(':')[0] }"/>
<property name="password" value="#{ #dbUrl.getUserInfo().split(':')[1] }"/>
</bean>
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.planit.persistence"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="POSTGRESQL"/>
</bean>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
Error occurs in the line of my spring.xml where I am defining my userRepository bean.
Thanks in advance.
#Repository is missing, try adding above the interface of the repo and remove bean declaration that is not allowed in Spring.
I believe you just need to remove this line:
<bean id="userRepository" class="com.planit.persistence.registration.UserRepository"/>
See the SpringData docs here.

Spring3 mybatis 3 mapper no such bean found exception

I am trying Spring 3 + Mybatis3 + mysql but didn't work out, tried almost all of the tutorials getting same exception, may be some one here can help me out
Following is the Error trace output and i have also attached list down the source code please help me out
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.triage.persistance.UserService com.triage.persistance.UserServiceImpl.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.triage.persistance.UserService] 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 39 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.triage.persistance.UserService] 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:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 41 more
** User.java **
package com.triage.domain;
public class User {
private long id;
private String name;
private String standard;
private int age;
private String sex;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
** UserService.xml**
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.triage.persistance.UserService">
<resultMap id="userResult" type="user">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="standard" column="standard" />
<result property="age" column="age" />
<result property="sex" column="sex" />
</resultMap>
<select id="getAllUsers" resultMap="userResult">
SELECT id, name, standard, age, sex FROM USER
</select>
</mapper>
** sqlmap-config.xml**
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<typeAliases>
<typeAlias type="com.triage.domain.User" alias="user"/>
</typeAliases>
</configuration>
** UserService.java **
package com.triage.persistance;
import java.util.List;
import com.triage.domain.User;
public interface UserService {
public List<User> getAllUsers();
}
** test-application context **
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
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/util
http://www.springframework.org/schema/util/spring-util-3.0.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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.triage" />
<context:property-placeholder location="classpath:properties/jdbc.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- jdbc template -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlmap-config.xml" />
<property name="mapperLocations"
value="classpath:mappers/*.xml" />
</bean>
</beans>
** My test case Execution point **
package com.triage.test;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import com.triage.domain.User;
import com.triage.persistance.UserService;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:test-applicationContext.xml")
#TestExecutionListeners(value = { DependencyInjectionTestExecutionListener.class })
public class HelloPortletTestContext extends AbstractJUnit4SpringContextTests {
#Autowired
private UserService userService; ** Error no such bean found error
//
// #Autowired
// private SqlSessionFactory sqlSessionFactory; // If i try this successfully found this object
#Test
public void testHelloAccount() {
List<User> items = userService.getAllUsers();
System.out.println(items.size());
Assert.assertTrue(!items.isEmpty());
Assert.assertTrue(true);
}
}
following two configurations into your spring context file
use spring-mybatis version 1.2.0
Change: Change your sqlSession factory to read your mappers files
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis/sqlmap-config.xml" />
<property name="mapperLocations" value="classpath:mybatis/mappers/*.xml" />
</bean>
Add following entry
<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.comcast.triage.persistance" />
</bean>

Categories

Resources