Spring3 mybatis 3 mapper no such bean found exception - java

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>

Related

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Customer is not mapped [from Customer]

org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: Customer is not
mapped [from Customer]
while everything is fine why it is showing this error
Bean class:
package com.luv2code.springdemo.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;
//#Table(schema = "web_customer_tracker", name = "customer")
#Table(name="customer")
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
DAO Impl class:
package com.luv2code.springdemo.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.luv2code.springdemo.entity.Customer;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
//get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
//List customers = new ArrayList<Customer>();
//create a query
Query<Customer> theQuery=currentSession.createQuery("from customer", Customer.class);
//currentSession.createQuery("from Customer", Customer.class);
//execute query and get result list
List<Customer> customers=theQuery.getResultList();
// return the results
/* Customer cus1=new Customer();
cus1.setEmail("a#gmail.com");
cus1.setFirstName("Abhishek");
cus1.setId(10);
cus1.setLastName("Kumar");
customers.add(cus1); */
return customers;
}
}
DATABASE:
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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="springstudent" />
<property name="password" value="springstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
It is because you are giving entity name in your Customer Entity,thus, same should be used in your queries(now name of the class cannot be referred in your queries). Try invoking the query with the same entity name mentioned(take care of cases as well).
Try as follows:
Query<Customer> theQuery=
currentSession.createQuery("from customer", Customer.class);
Here I have matched the entity name mentioned in #Entity(name="customer") in your query.
I didnt go through all your code but, in sessionFactory bean of xml,
Try changing <property name="packagesToScan" value="com.luv2code.springdemo.entity" /> to <property name="packagesToScan" value="code.luv2code.springdemo.entity" />.
Your actual Customer entity lives in package code.luv2code.springdemo.entity
, though you have used com.luv2code.springdemo.entity. So it is scanning wrong package. This might be the problem.
if you are using check if the packages of C3p0 of correct for hibernate, Iam using the following and it works for me.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.26.Final</version>
</dependency>
Also in contrast to the above answers, In Hibernate it is always the entity name for HQL even though you have added #Table(name="customer")
Query<Customer> theQuery=
currentSession.createQuery("from Customer", Customer.class);
Let me know if this still does not work for you
Try like this :
Query theQuery=currentSession.createQuery("from Customer");
In Customer class
#Entity --> hibernate takes by Default as #Entity(name = "Customer")
though your database table is customer it reads as Customer because annotated class hibernate configures as Customer
so update,
List<Customer> li = session.createQuery("from Customer").list();

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.

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>

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.

Hibernate does not save data into DB?

I have a form where i input details, but when i click on save it does not get saved in the database... though the table does get created.
My Contact POJO
package your.intermedix.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="USER")
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String email;
private String lastname;
private String designation;
#Id
#GeneratedValue
#Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="DESIGNATION")
public String getDesignation(){
return designation;
}
public void setDesignation(String designation){
this.designation = designation;
}
#Column(name="EMAIL")
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
#Column(name="LASTNAME")
public String getLastname(){
return lastname;
}
public void setLastname(String lastname){
this.lastname= lastname;
}
#Column(name="FIRSTNAME")
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String toString()
{
return "designation = '" + designation + "',email='"+ email +"', lastname='"+ lastname +"', name = '" + name + "'";
}
}
My Application-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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
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">
<!-- Turn on AspectJ #Configurable support -->
<context:spring-configured />
<context:property-placeholder location="classpath*:*.properties" />
<context:component-scan base-package="your.intermedix"/>
<context:annotation-config/>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- a PlatformTransactionManager is still required -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- (this dependency is defined somewhere else) -->
<property name="dataSource" ref="myDataSource"/>
</bean>
<!-- Turn on #Autowired, #PostConstruct etc support -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>your.intermedix.domain.Contact</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"/>
<property name="username" value="monty"/>
<property name="password" value="indian"/>
</bean>
</beans>
I am not getting any sort of error.... in the console.
Updated code..
package your.intermedix.services;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import your.intermedix.domain.Contact;
import your.intermedix.services.IContact;
#Service
public class ContactSerImpl implements IContact {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Transactional
public void saveContact(Contact contact) {
System.out.println("Hello Guru contact");
System.out.println(contact);
hibernateTemplate.saveOrUpdate(contact);
}
public void hello() {
System.out.println("Hello Guru");
}
}
My Service class where i the print statements work
You need a running transaction. Spring transaction management is the way to go if using HibernateTemplate. Read the documentation. It's too long to include in an answer, but here is in short:
you need to define a transaction manager as a spring bean
you need <tx:annotation-driven />
you need to annotate your transactional methods with #Transactional
I don't know the Spring-Hibernate framework, but often when data is not written it menas it is not flushed to the databackend. What gives you
System.err.println(hibernateTemplate.getFlushMode());

Categories

Resources