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

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.

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.

How to create emdedded H2 DB with spring(transactional) and hibernate in java desktop application?

I am trying to create a project with embedded h2 db, and using spring framework with hibernate. My database will be created in initialize time if not exist. My development platform is intellij.
Problem is that when i run the application
#Autowired
private IPersonService personService; // comes null?
here is my classes and config files.
myDB.sql:
CREATE TABLE IF NOT EXISTS personel(
id IDENTITY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age VARCHAR(100));
hibernate.properties:
db.driverClassName=org.h2.Driver
db.url=jdbc:h2:~/h2SpringProject/database/SpringSample;mv_store=false;mvcc=false
db.username=admin
db.password=
here is my hibernate-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.springapp"/>
<context:annotation-config/>
<context:property-placeholder location="hibernate.properties"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
<property name="driverClassName" value="${db.driverClassName}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="suppressClose" value="true"/>
</bean>
<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
<jdbc:script location="myDb.sql"/>
</jdbc:initialize-database>
<bean id="hibernateCfgProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
</prop>
</props>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties" ref="hibernateCfgProperties"/>
<property name="packagesToScan" value="com.springapp.model"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Person class
#Entity
#Table(name = "personel")
public class Personel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "age")
private String age;
.......
An IPersonDao interface and here is implemented class
#Component
public class PersonelDaoImpl implements IPersonelDao {
#Autowired
private SessionFactory sessionFactory;
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void savePersonel(Personel personel) {
getCurrentSession().saveOrUpdate(personel);
}
#Override
public void deletePersonel(long id) {
getCurrentSession().delete(id);
}
#Override
public List<Personel> getPersonels() {
return getCurrentSession().createQuery("from Personel").list();
}
}
There is an IPersonService interface and here is implemented class
#Service("PersonelService")
public class PersonelServiceImpl implements IPersonelService {
#Autowired
private IPersonelDao personelDao;
#Override
#Transactional
public void savePersonel(Personel personel) {
personelDao.savePersonel(personel);
}
#Override
#Transactional
public void deletePersonel(long id) {
personelDao.deletePersonel(id);
}
#Override
#Transactional
public List<Personel> getPersonels() {
return personelDao.getPersonels();
}
}
here is my main class
public class MainApp {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = new ClassPathXmlApplicationContext("hibernate-config.xml");
ForExample a = new ForExample();
a.execute();
}
}
#Component
public class ForExample {
#Autowired
private IPersonelService personelService;
public void execute(){
Personel p = new Personel();
p.setName("thats Ok!");
p.setAge("614345");
personelService.savePersonel(p);
}
}
public class MainApp {
public static ApplicationContext applicationContext;
private static IPersonelService personelService;
public static void main(String[] args) {
applicationContext = new ClassPathXmlApplicationContext("hibernate-config.xml");
personelService = applicationContext.getBean(IPersonelService.class);
Personel p = new Personel();
p.setName("thatsOK!");
p.setAge("614345");
personelService.savePersonel(p);
}
}
Because of spring does not recognise new operator in run time..

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

How to fix "Duplicate property mapping" exception?

xml file to map a new table from my db but when I start the project I get a Duplicate property mapping error that I cannot understand and resolve. Here is my hibernate cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="session1">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/realestate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<mapping resource="entities/users.hbm.xml"/>
<mapping resource="entities/adminstration.hbm.xml"/>
<mapping resource="entities/seller.hbm.xml"/>
<mapping resource="entities/buyer.hbm.xml"/>
<mapping resource="entities/renter.hbm.xml"/>
<mapping resource="entities/leeser.hbm.xml"/>
<mapping resource="entities/house.hbm.xml"/>
<mapping resource="entities/userSellsHouse.hbm.xml"/>
<mapping resource="entities/userRentsHouse.hbm.xml"/>
<mapping resource="entities/messages.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The messages.hbm.xml file:
<?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="entities.Message" table="MESSAGES" schema="realestate">
<id name="messageID" type="int">
<column name="messsageID" />
</id>
<property name="Date" type="java.lang.String">
<column name="Date" />
</property>
<property name="SenderID" type="java.lang.Integer">
<column name="Sender" />
</property>
<property name="ReceiverID" type="java.lang.Integer">
<column name="Receiver" />
</property>
<property name="Message" type="java.lang.String">
<column name="Message" />
</property>
<property name="Theme" type="java.lang.String">
<column name="Theme" />
</property>
</class>
</hibernate-mapping>
and the Message persisent class:
public class Message {
int MessageID;
int SenderID;
int ReceiverID;
String date;
String message;
String theme;
public int getMessageID() {
return MessageID;
}
public void setMessageID(int messageID) {
MessageID = messageID;
}
public int getSenderID() {
return SenderID;
}
public void setSenderID(int senderID) {
SenderID = senderID;
}
public int getReceiverID() {
return ReceiverID;
}
public void setReceiverID(int receiverID) {
ReceiverID = receiverID;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
}
and here's the error
...
Caused by: org.hibernate.MappingException: Duplicate property mapping of SenderID found in entities.Messages
at org.hibernate.mapping.PersistentClass.checkPropertyDuplication(PersistentClass.java:515)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:505)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at database.HibernateUtil.<clinit>(HibernateUtil.java:15)
... 46 more
Edit: I tried commenting out the <mapping resource="entities/messages.hbm.xml"/> from the cfg file and I still get the same error.
Edit2: The above is from a java EE project, I copied paste everything in a simle java project and it worked fine. Any suggestion?
Edit3: I added the final modifier to messages class to be sure that it cannot be inherited
Please go through the following link, this might help you...
Hibernate ORMHHH-2598
Mapping a collection of entities from two different classes with the same collection name results in duplicate backref property exception if collection keys are not null

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